最近、このコードについて質問しましたが、別のコードがありました。テストで文字を入力すると、次のエラーが発生するため、整数のみを受け入れるようにスキャナーをセットアップします。
java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at RockPaperScissorsTest.main(RockPaperScissorsTest.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
では、スキャナーで整数のみを許可するにはどうすればよいでしょうか? そのため、1 つ入力しても、スキャナー ボックスには何も表示されません。助けてくれてありがとう!以下、プログラム全体です。
import java.util.Scanner;
public class RockPaperScissorsTest {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System. in );
int P1;
int P2;
do {
System.out.println("Player 1, choose 1 for rock, 2 for paper, or 3 for scissors.");
P1 = input.nextInt();
} while (P1 != 1 && P1 != 2 && P1 != 3);
System.out.println("");
System.out.println("");
System.out.println("");
do {
System.out.println("Player 2, choose 1 for rock, 2 for paper, or 3 for scissors.");
P2 = input.nextInt();
} while (P2 != 1 && P2 != 2 && P2 != 3);
if (P1 == 1 & P2 == 1)
System.out.println("It's a tie!");
if (P1 == 1 & P2 == 2)
System.out.println("Player 2 wins!");
if (P1 == 1 & P2 == 3)
System.out.println("Player 1 wins!");
if (P1 == 2 & P2 == 1)
System.out.println("Player 1 wins!");
if (P1 == 2 & P2 == 2)
System.out.println("It's a tie!");
if (P1 == 2 & P2 == 3)
System.out.println("Player 2 wins!");
if (P1 == 3 & P2 == 1)
System.out.println("Player 2 wins!");
if (P1 == 3 & P2 == 2)
System.out.println("Player 1 wins");
if (P1 == 3 & P2 == 3)
System.out.println("It's a tie!");
}
}