有人可以告訴我我的代碼有什麼問題,如下所示?第一種情況非常好,但第二種和第三種情況引發異常:我的掃描儀代碼有什麼問題?
這是否與情況2和3開始時的while循環有關?
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;
}
}
異常在線程 「主」 java.util.NoSuchElementException
在java.util.Scanner.throwFor(Scanner.java:862)
在java.util.Scanner中。下(Scanner.java:1371)
在HelloWorld.main(HelloWorld.java:64)
異常是java.util.NoSuchElementException –
請編輯您的問題,以包含您得到的任何錯誤的完整堆棧跟蹤。 – azurefrog
[NoSuchElementException與Java.Util.Scanner]可能的重複(http://stackoverflow.com/questions/13729294/nosuchelementexception-with-java-util-scanner) – David