Java - nextLine(); within a switch statement - java

I have a switch statement acting as a menu, in this I am trying to read the users input. Currently I am using variable=in.next(); and this works. However it will only read one word and at points the user may need to enter more, so I tried using variable=in.nextLine();, which compiles, but when I run the program, I select my choice from the menu, and it skips the reading in and return to the menu.
Any help would be appreciated, thanks :)

Just use:
name=in.nextLine();
and
String choice = in.nextLine();
This should be in the constructor, and at the top of runApp.
That way, you're not leaving the new line in the buffer (where it will be used for e.g. dp).
You should have:
dp=in.nextLine();
as described in your question.

You either have to strip the newline character \n from the user input or assume it's there in your switch statement.
Pretty much because you decided to use nextLine() the user input to the computer will look like this
f\n
So just compare the strings accordingly!

OK I think I am too inept at Java and have put my question badly.
When I take the users input it takes only 1 word, I want it to take everything they put basically, and when I use nextLine, this just skips the reading and takes me back to selecting a choice.

Switch selector can be only integer, short, char or enum. String cannot be used as a switch selector.
If I understood you correctly you would like to control your flow using words entered by user. If you have predefined list of words I'd suggest you to use enum:
enum Words {
start, stop, beep,
}
Now user enters a word beep. You can say:
Words command = Words.valueOf();
///
switch (command) {
case start: /* start something */ break;
case stop: /* stop something */ break;
case beep: /* beep!!! */ break;
default: throw new IllegalArgumentException("Unknown command " + command);
}

Related

Im looking to ask for user input, but instead, my code returns me back to the beginning without giving the chance to enter input

so, i am looking to write code which firstly asks for user input in order to run the desired operation, this element of my code is working fine, but after selecting one of the options from the first menu i am asking the user for a second string input which i would like to turn to both lower and uppercase, but instead of letting me enter an input, the program just goes back to the original screen showing all options.
this is my code asking for a string input that isnt working:
else if(choice1==1)
{
System.out.println("================================="+"\n"+"You have chosen to convert a given string to upper case and lowercase, please enter your string: "+"\n");
choice2 = sc.nextLine();
System.out.println("Your lowercase string: "+choice2.toLowerCase()+"\n"+"Your uppercase string: "+choice2.toUpperCase);
}
Cheers for the help guys!!
You need to consume the end of line character:
choice1 = sc.nextInt();
sc.nextLine(); // consume the end of line
// Now your program continues as before.
// Probably you have an 'if' here, I don't know, you
// haven't shown it

Java Scanner hasNextInt() causing infinite loop

What I am trying to do is have the user enter a lot of numbers and then hit enter, and then store all those numbers onto a stack at once. My thought was to use a loop to go through all the numbers and push them onto the stack like so:
Stack<Integer> mainBin = new Stack<Integer>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
mainBin.push(scanner.nextInt());
}
However, even after I press enter many times without entering anything new, it still stays in the loop. Any suggestions?
Scanner.hasNextInt() skips over whitespace to find the next token. So it reads and skips over all your Enter presses. Then it waits for more input, because there may be more input coming.
In a Linux terminal, you can press Ctrl-D (maybe Cmd-D on OS X?) to send an end-of-file marker, which tells the application that there is no more input coming (this should be done at the start of a line). This answer suggests that Ctrl-Z is the equivalent in Windows' command prompt.
Alternatively, you could have some special input that your application reads. #phatfingers commented that you could specify the number of values to read as the very first input. You could also have a special value to signify the end (0 or -1 are common choices, based on the application's needs), or maybe even use a non-numeric token like "end".
Your example uses scanner.hasNext(). Use scanner.hasNextInt() instead.

How to make multiple lines after System.out.println in the cmd?

import java.util.Scanner;
public class ChristmasSong{
public static void main (String[] args)
Scanner scanner = new Scanner(System.in);
System.out.println("What would like to do? (Do one action) (Do another action) Exit");
This is the beginning of my program. Using Java, how do I make the expression inside the System.out.println appear in mulitple lines on the cmd when I execute the program?
Like I want to make it say
What would you like me to do?
(Do one action)
(do another action)
exit
instead of
What would you like me to do? (Do one action) (Do another action) Exit
and I want the user to type in their option and make the program act according to the option. This is more of format and style kind of question. It probably sounds stupid, but I'm a beginner. Just a week of experience in class and I want to get better. If you could help me out. That would be awesome. Thanks.
System.out.println() outputs line breaks using the platform's preferred line separator
\n The newline (line feed) character ('\u000A')
System.out.println("What would you like me to do?");
System.out.println("(Do one action)");
System.out.println("(do another action)")
System.out.println("exit");
alternatively
System.out.println("What would you like me to do?\n(Do one action)\n(do another action)\nexit");
The second version outputs newline characters, which is likely to be inappropriate on Windows or Mac OS.
For more info regarding performance have a look System.out.println() vs \n in Java
In Java 15, a new feature called Text Blocks are available while in Java 13 and Java 14, these are preview features.
Text blocks help to achieve the results more elegantly and are readable than the accepted answer.
Text blocks starts with three double-quote marks """
Inside the text blocks, we can freely use newlines and quotes without the need for escaping line breaks.
Example:
String text = """
Players take turns marking a square.
Only squares not already marked can be picked.
Once a player has marked three squares in a row, he or she wins!
If all squares are marked and no three squares are the same, a tied game is declared.
Have Fun!""");

nextLine().charAt(0) inside a switch statement

I'm making a very basic calculator program and ran into a problem that's baffled my mind the entire time.
Code:
switch(operation){
case 'a':
case 'A':
addition(n);
operation = n.nextLine().charAt(0);
break;
When I run the program and enter either characters (proceeding code uses Scanner object n to determine which char I type in), the method addition(n) works as intended. Basically the switch statement is inside a while loop so that it executes until I enter 'E', and the 5th line in the code I have above will change the char operation so that it does not execute the addition switch block over and over. The 5th line operation = n.nextLine().charAt(0); will give me an error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
Why is it giving me this error? What troubles my mind more is my default inside the switch is structured similarily yet the exact same code will work for it.
default:
System.out.println("Invalid entry. Refer to above menu and input"
+ " your choice of operation.");
operation = n.nextLine().charAt(0);
break;
Many thanks for your time.
EDIT: If I comment out the method addition(n), the 5th line will work as fine, allowing me to change my char operation. Why is the 4th line responsible for this?
Please use n.next().charAt(0) instead of n.nextLine().charAt(0). I think beacuse our task is to read the first character why should I consider a whole line of text may contain many words, spaces, special characters etc. , while I can get the first character from the first word and it is efficient, that's why java does not allow. :)
Welcome !

java calculator randomly outputted line

So I've just started java with a tiny bit of experience from a few other languages. I tried to make this basic calculator and had a lot of problems but managed to resolve most of them. The last thing that I can't seem to understand is a randomly triggered "This is an invalid input", every time my program runs once. "..." refers to irrelevant code. Everything else seems to work fine. Thanks in advance!
import java.util.Scanner;
public class Calc {
...
System.out.println("Would you like to use the calculator?(Y/N)");
while(use){
String usage=in.nextLine().toLowerCase();
if(usage.equals("n")){use=false;}
//input
//operations
else if(usage.equals("y")){
...(calculator code)
System.out.println("Continue use? (Y/N)");
}
else {System.out.println("That is not a valid input");}
}
}
}
After running my code a few times, my output is
Would you like to use the calculator?(Y/N)
Y
Please input an operation: +,-,*,/,%, ^, or root
+
Calculator: Please input your first number.
1
Now enter your second number.
2
Calculating
3.0
Continue use? (Y/N)
That is not a valid input <-- right there is the confusing part, why is that triggered?
Y
Please input an operation: +,-,*,/,%, ^, or root
Full code is on pastebin, if you somehow need it. http://pastebin.com/Qee2Hxe3
I checked the full code, and right before the loop first reiterates, there is a call to in.nextDouble(), this method reads a double but does not consume the line end, which makes the next in.readLine() return \n immidiately and the succeeding test fails.
A simple solution is to manually consume the line-end:
System.out.println(ans);
System.out.println("Continue use? (Y/N)");
in.nextLine();
I tested your code and found that a solution is to declare your scanner inside your while loop, like so:
while (use) {
Scanner in = new Scanner(System.in);
String usage = in.nextLine().toLowerCase();
Here's what the problem is: first, you are entering your while loop, and usage is set equal to in.nextLine(). Since there is no next line, it waits for you to enter one. You enter yes, after which you enter your formula. Then it returns the answer, and goes back to the top of the while loop. Once again, usage is set to equal in.nextLine, but there is already a next line (a blank one) and so usage is set to equal an empty String ("") which is neither "y" or "n". Then it immediately goes to the "else" option at the end and prints the "invalid" message.
Re-assigning your scanner through each iteration of your while loop fixes this problem.
The last input you read in your code when calculating is this:
num2=in.nextDouble();
This reads the next characters and convert it to a double. However when you input your number, you also hit enter.
This means that after the double is read, there is still a newline character left in the input buffer.
As the code goes back to the String usage=in.nextLine().toLowerCase(); , you will now read this newline.
You could just ignore empty input, by e.g. doing
String usage=in.nextLine().toLowerCase().trim();
if (usage.isEmpty()) {
continue;
}

Categories