Tuesday, 7 March 2017

java - Scanner skipping input for first input on loop



I have a program to write to a text file, just using basic input from the scanner. I have it so it goes through the questions then a yes no to add another input. When the user(or tester being me) inputs y to do it again, it asks the 2 top questions at the same time so it does not get the input for the first question, any reason why this is happening? Here is an example
Would you like to create another entry? Y/N
y
What is the course code for the assignemnt?
What is the name of the assignment?



do{

System.out.println("What is the course code for the assignemnt?")
course = s.nextLine();
System.out.println("What is the name of the assignment?");
gName = s.nextLine();
System.out.println("What did you get on the assignment?");
yourGrade = s.nextLine();
System.out.println("What was the assignment out of?");
gMax = s.nextLine();
System.out.println("What was the assignment weighted?");
gWeight = s.nextLine();


pw.printf("%s|%s|%s|%s|%s",course, gName, yourGrade, gMax, gWeight);
pw.println("");
System.out.println("Would you like to create another entry? Y/N");
YN = s.next().charAt(0);
}
while(YN == 'Y' || YN == 'y');
pw.close();
}


Answer



YN = s.next().charAt(0); won't comsume the end-of-line character which will get consumed by the next nextLine (that is on the next iteration), so you need to to another nextLine after it. Or read a line with nextLine and use charAt(0) on that like this: YN = s.nextLine().charAt(0);


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...