Do not request input

I have it:

Scanner input = new Scanner ( System.in ); int selection = input.nextInt(); if (selection == 1) { System.out.println("Please enter a string: "); String code = input.nextLine(); } 

However, when it gets to Please enter a string, it does not ask for input. It just goes to the rest of the program.

+4
source share
3 answers

Scanner waits for nextInt() until the user presses the enter button. When this happens, it consumes numbers, but not a new line symbol. Thus, the next call to nextLine() immediately returns with an empty String as the result.

This should fix:

 int selection = input.nextInt(); input.nextLine(); if (selection == 1) { System.out.println("Please enter a string: "); String code = input.nextLine(); 

But my preferred way is to always use nextLine and parse separately:

 String selectionStr = input.nextLine(); //consider catching a NumberFormatException here to handle erroneous input int selection = Integer.parseInt(selectionStr); if (selection == 1) { System.out.println("Please enter a string: "); String code = input.nextLine(); //... 
+6
source

to try:

 input.nextLine(); 

after your nextInt ();

 Scanner input = new Scanner(System.in); int selection = input.nextInt(); input.nextLine(); System.out.println(selection); if (selection == 1) { System.out.println("Please enter a string: "); String code = input.nextLine(); } 
0
source

simple and graphic input:

 String str=JOptionPane.showInputDialog(null,"Message","Title",JOptionPane.QUESTION_MESSAGE); 
0
source

Source: https://habr.com/ru/post/1345159/


All Articles