+ 1

How much does input order matter?

Here is my question, when I write my code block waiting for inputs as the following, it skips my input to the last question when run in Eclipse. import java.util.Scanner; class Inputs{ public static void main(String[]args){ Scanner info = new Scanner(System.in); System.out.println("What's your name?"); String name = (info.nextLine()); System.out.println("How old are you?"); int age = (info.nextInt()); System.out.println("How cool are you?"); String cool = (info.nextLine()); System.out.println("Your name is, " + name +". You are " + age + " years old." + "You are " + cool + " cool." ); } } However, if I switch age to the last input, it waits for my last input before giving me back the statement at the end. import java.util.Scanner; class Inputs{ public static void main(String[]args){ Scanner info = new Scanner(System.in); System.out.println("What's your name?"); String name = (info.nextLine()); System.out.println("How cool are you?"); String cool = (info.nextLine()); System.out.println("How old are you?"); int age = (info.nextInt()); System.out.println("Your name is, " + name +". You are " + age + " years old." + "You are " + cool + " cool." ); } } Is there a reason for this or something I am missing?

25th Jan 2017, 9:12 PM
Sean McKee
1 Answer
0
What do you mean by "it skips my input to the last question"? after you type an input into the console or before? To where exactly in the code it skips to? Anyway, I think the problem is with the "info.nextLine()", As it "advances the scanner past the current line and returns the input that was skipped" (By the java documantion). Try to switch all of the "info.nextLine()" with "info.next()" and see what happens.
25th Jan 2017, 9:36 PM
Nathan
Nathan - avatar