我最近问了一个关于这段代码的问题,但我还有另一个问题。我想将扫描仪设置为只接受整数,因为当我在测试中输入一个字母时,我得到这个错误:
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)
那么,我该怎么做才能只允许扫描仪中的整数?因此,如果您键入一个,它不会在扫描仪框中显示任何内容。谢谢您的帮助!下面是整个程序。
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!");
}
}