Can anybody tell me what is wrong with my code as shown below? The first case works perfectly fine but the second and third case throws an exception :
Does this have something to do with the while loops at the start of case 2 and 3?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int option = scan.nextInt();
switch (option) {
case 1: int line = scan.nextInt();
for (int i = 0; i < line; i++){
String operator = scan.next();
int n1 = scan.nextInt();
int n2 = scan.nextInt();
Boolean no1 = (n1 == 1) ? true:false;
Boolean no2 = (n2 == 1) ? true:false;
if (operator.equals("AND")) {
int result = (no1 && no2) ? 1:0;
System.out.println(result);
} else {
int result = (no1 || no2) ? 1:0;
System.out.println(result);
}
}
break;
case 2: while (!scan.nextLine().equals("0")) {
String operator = scan.next();
int n1 = scan.nextInt();
int n2 = scan.nextInt();
Boolean no1 = (n1 == 1) ? true:false;
Boolean no2 = (n2 == 1) ? true:false;
if (operator.equals("AND")) {
int result = (no1 && no2) ? 1:0;
System.out.println(result);
} else {
int result = (no1 || no2) ? 1:0;
System.out.println(result);
}
}
break;
case 3: while (scan.hasNextLine()) {
String operator = scan.next();
int n1 = scan.nextInt();
int n2 = scan.nextInt();
Boolean no1 = (n1 == 1) ? true:false;
Boolean no2 = (n2 == 1) ? true:false;
if (operator.equals("AND")) {
int result = (no1 && no2) ? 1:0;
System.out.println(result);
} else {
int result = (no1 || no2) ? 1:0;
System.out.println(result);
}
}
break;
default: System.out.println("Error");
break;
}
}
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at HelloWorld.main(HelloWorld.java:64)