現在、私はswitch文を使って遊んでいます。私はswitch文を使って複数のループがあるときに問題に遭遇します。Javaの複数のswitch文 - NoSuchElementException
私は二switchステートメントを終了すると(1まで行くためには)、Javaはjava.util.NoSuchElementException
スロー、と私は
switchOne = sc.nextInt();
ので、新しいユーザの入力をトリガすることになっている理由はかなりわかりませんか?
私は誰かが私にこれについていくつかの光を投げるのを助けることを望んでいます。 scanner
をtry-with-resources
なしで使用しようとしましたが、同じエラーが発生します。
public static void main(String[] args) {
int switchOne = 0;
int switchTwo = 0;
boolean breakAdmin = false;
try(Scanner sc = new Scanner(System.in)) {
while(true) {
System.out.println("Select one of the options below");
System.out.println("1: Browse books");
System.out.println("2: Get a coffe");
System.out.println("3: See previously checkouts");
System.out.println("0: Exit");
System.out.print("Option: ");
switchOne = sc.nextInt();
switch(switchOne) {
case 0:
return;
case 1:
System.out.println("!!You choose to browse over books, woohoo!!");
break;
case 2:
System.out.println("!!Sit & relax");
break;
case 3:
System.out.println("!!Let me get that list for you");
break;
case 99:
System.out.println("We welcome you!");
try(Scanner sc2 = new Scanner(System.in)) {
while(!breakAdmin) {
System.out.println("0: exit");
System.out.println("1: something");
switchTwo = sc2.nextInt();
switch(switchTwo) {
case 0:
breakAdmin = true;
break;
case 1:
System.out.println("!!admin 1");
break;
default:
System.out.println("!!This is the default case");
break;
}
}
}
breakAdmin = false;
break;// case 99 ends
default:
System.out.println("!!This is the default case");
break;
} // switch block ends
} // while loop ends
} // try with resources ends
}
「switchOne = sc」の前に 'sc.nextLine();'を実行するとどうなりますか? nextInt(); '? – Gendarme
ストリームの周りに親指のルールがあります: "あなたがそれを開いていない場合は、閉じないでください"。 'Scanner.close()'を呼び出すと 'Readable'が閉じられますので、try-with-resourcesを' Scanner'ラップ 'System.in'で使用しないでください。 JVMが行った)。 –