简体   繁体   English

仅允许使用Java扫描器输入整数

[英]Only allow input of integers with java scanner

I recently asked about a question about this code, but I had another. 我最近问了有关此代码的问题,但我有另一个问题。 I want to setup the scanner to only accept integers, because when I enter a letter in testing, I get this error: 我想将扫描仪设置为仅接受整数,因为在测试中输入字母时会出现以下错误:

 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)

So, what can I do to only allow integers in the scanner? 因此,我该怎么做才能只允许扫描仪中的整数? So if you typed one, it would not show anything in the scanner box. 因此,如果您键入一个,它将不会在扫描仪框中显示任何内容。 Thanks for the help! 谢谢您的帮助! Below is the entire program. 以下是整个程序。

 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!");
}

} }

You have a couple of options: 您有两种选择:

  • Use Scanner.hasNextInt() to see if an integer can be read; 使用Scanner.hasNextInt()查看是否可以读取整数。 note that you will have to skip the token with next() if it is not an integer so you don't get "stuck". 请注意,如果它不是整数,则必须使用next()跳过令牌,这样就不会出现“卡住”的情况。
  • Read the token as a string and use Integer.parseInt() , ignoring tokens that cannot be parsed as an integer. 以字符串形式读取令牌,并使用Integer.parseInt() ,忽略无法解析为整数的令牌。

I think a solution is to use a while block, and test until the input is an Integer, like this: 我认为一种解决方案是使用while块,并测试直到输入为Integer,如下所示:

int choice;
Scanner sc = new Scanner(System.in);
String input = "a";
boolean notAnInteger = true;
while(notAnInteger){
     input = sc.next();
     try{
         choice = Integer.parseInt(input);
         notAnInteger = false;
     }catch(Exception e){
         System.out.println("Not an integer");
     }

}

I haven't tested this but I think it should work ;) 我没有测试过,但是我认为它应该可以工作;)

     boolean testing = false;
     String pos = "";
     while(true)
     {
     testing = false;   
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter the integer value.... ");
     pos = sc.next();
     for(int i=0; i<pos.length();i++)
     {
         if(!Character.isDigit(pos.charAt(i)))
             testing = true;
     }
     if(testing == true)
     {
         System.out.print("Enter only numbers..   ");
         continue;
     }

     else
     {
         int key = Integer.parseInt(pos);
         // Your code here....
         break;
     }

There are several options here 这里有几种选择

  1. You could surround your input.nextInt() inside a try/catch block and catch the InputMismatchException. 您可以将您的input.nextInt()包围在try / catch块中,并捕获InputMismatchException。 You could then prompt them again or handle this however you like. 然后,您可以再次提示他们,也可以根据需要进行处理。

     try { P1 = input.nextInt(); } catch (InputMismatchException e) { //Handle how you choose. } 
  2. Scanner has a hasNextInt() method which will evaluate to true if the next token is an int. 扫描器具有hasNextInt()方法,如果下一个标记为int,则该方法的值为true。

     if(input.hasNextInt()){ P1 = input.nextInt(); } else { //Handle how you choose. } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM