Active5 years, 10 months ago
The code will compile, but there seems to be an error with my menu. The user will select one of the choices and the program should execute, but When choosing a selection nothing happens. Here is the code:
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. The default case can be used for performing a task when none of the cases is true. Java switch case statement FAQ: Can you provide an example of a Java switch/case statement syntax? Here's a sample Java method that takes an int argument and attempts to turn that int into a month string, using a Java switch case statement to make that decision: private String getMonthAsString(int.
Here is the what it looks like when run:
Sample Program In Java String
user2943817user2943817
6 Answers
![Java Java](/uploads/1/2/4/7/124752063/215100157.jpg)
Well, you definitely need to move code which gets input inside the loop :
Otherwise, you input once and switch on that input indefinitely (unless it is 'q')
Edit : You also need to change terminating condition to
for it to work.
kiruwkakiruwkawhile (!choice.equals('q'));
for it to work.
7,35311 gold badge2121 silver badges3636 bronze badges
This also depends on which version of the JDK they're using.
crownedzerocrownedzero36311 gold badge44 silver badges1717 bronze badges
Few things:
You read input only once - outside of do..while - probably not what you want (otherwise you'd be stuck in infinite loop).most likely the intent was this:
while ((choice = scan.nextLine()) != 'q');
As far as why you don't see anything when running, it depends on what myGeek.getName()
does.As name suggests its a simple getter, if this is a case then it returns the name but it does not print anything on the screen.АлексейАлексей
i think you want something like this:
if not --->>>> for what you need do -> while??
and check, if your java is 7 or heighter, and check your getMethods() -> if thay return anything
Andrew EvtAndrew Evt
One issue you have, as mentioned by @rgettman, is that comparing
String
s in Java using or !=
will compare the Object reference of the String
not the value; basically are the two String
s the same Object? In this case (and most cases) you want to compare the value. Change
while (choice != 'q');
to while (!choice.equals('q'));
to compare the values.A slightly different explanation:
Right now you are entering a character, say 'a', matching your
case
for 'a' and breaking from the switch/case. However when your program gets to the while
it basically checks whether choice
is'q'
so your program goes back into the do/while
loop.knoightknoight
Your loop (do {} while(condition)) will loop infinite when you enter some string different 'q' because condition always is true.try with :
ThangnvThangnv36233 gold badges66 silver badges2020 bronze badges