Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java scanner not storing string properly

Tags:

java

I am trying to create a menu in the console and have the user select an option, for some reason when I run the application it goes straight to the else, bypassing options a-d.

import java.util.Scanner;

public class UserChoice {


 public static void main(String[] args) 
{
    boolean status = true;
    while (status == true)
    {
    System.out.println("");
    System.out.println("MENU");
    System.out.println("");
    System.out.println("A : String Functions");
    System.out.println("B : Simple Arithmetic Functions");
    System.out.println("C : Temperature Conversion");
    System.out.println("D : Sequences");
    System.out.println("E : Exit Application");
    System.out.println("");
    System.out.println("Please make a selection.");
            Scanner keyboard = new Scanner(System.in);
    String choice =null;
    choice = keyboard.nextLine();





    if (choice == "a" || choice == "A")
    {
        StringFunctions();
    }

    else if (choice == "b" || choice == "B")
    {
        ArithmeticFunctions();
    }

    else if (choice == "c" || choice == "C")
    {
        TemperatureConversion();
    }

    else if (choice == "d" || choice == "D")
    {
        Sequences();
    }

    else if (choice == "e" || choice == "E")
    {
        System.exit(0);
    }
    else 
    {
        System.out.println("You have entered an invalid selection, please choose again.");

    }
    }

}
like image 239
user1776071 Avatar asked Mar 02 '26 17:03

user1776071


1 Answers

All String/Object comparisons should use equals() method instead of == (except String literals)

if (choice.equals("a") || choice .equals( "A")){....}

Apply same change to other else/if blocks also.

== compares reference equality. equals() method checks for content equality.

like image 155
kosa Avatar answered Mar 05 '26 05:03

kosa