Issue
So basically I have this project for school and it contains a switch statement within a while loop.
Lets say I input "1" and its runs the code within case "1". And then it should break after. But the default code always gets run as well.
case "1":
counter = arrayLength();
if (counter != 20) {
System.out.print("Student name: ");
students[array] = sc.nextLine();
System.out.print("Student mark: ");
marks[array] = sc.nextByte();
array++;
System.out.println("Student added succsessfully.");
} else {
System.out.println("You can only add 20 students.");
}
break;
Here is the default code:
default:
System.out.println("Incorrect input. Please try again.");
Here is the output:
1
Student name: Test
Student mark: 50
Student added successfully.
Incorrect input. Please try again.
I am pretty confident that I have my code right, but if there is something I am missing, please tell me how to fix it, thanks.
Solution
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true){
switch(in.nextLine()){
case "1":
System.out.print("Student name: ");
String name = in.nextLine();
System.out.print("Student mark: ");
byte b = in.nextByte();
in.nextLine(); //consumes trailing '\n'
System.out.println("Student added succsessfully.");
break;
default:
System.out.println("Incorrect input. Please try again.");
}
}
}
use the in.nextLine() to consume the trailing \n after nextByte(). The explanation is in the link provided in the comment.
Answered By - experiment unit 1998X
Answer Checked By - Mildred Charles (JavaFixing Admin)