【问题标题】:How to check the type of a user input in Java?如何在 Java 中检查用户输入的类型?
【发布时间】:2015-07-30 14:56:59
【问题描述】:

我想知道如何对用户输入进行类型检查。这里我有一个简单的测试来检查用户输入是否在 1 到 10 之间。我想设置它以便用户也可以输入字母,主要是我可以使用输入 'q' 来退出程序。

扫描仪有可以打字检查的部分吗?我的想法是有一个if语句:如果用户输入type int continue,如果不是type int,检查是否是q退出程序,否则输出这是一个错误。以下是我到目前为止的内容,由于类型不匹配,因此在输入数字时会抛出一个表达式。

public static void main(String[] args) {
    //Create new scanner named Input
    Scanner Input = new Scanner(System.in);
    //Initialize Number as 0 to reset while loop
    int Number = 0;

    do
    {
        //Ask user to input a number between 1 and 10
        System.out.println("At anytime please press 'q' to quit the program.");
        System.out.println();
        System.out.print("Please enter a number between 1 and 10:");
        Number = Input.nextInt();

        if (Number == 'Q'|| Number == 'q')
        {
            System.out.println("You are now exiting the program");
        }
        else if (Number >= 1 && Number <= 10)
        {
            System.out.println("Your number is between 1 and 10");
        }   
        else
        {
            System.out.println("Error: The number you have entered is not between"
                    + " 1 and 10, try again");
        }
    }
    //Continue the loop while Number is not equal to Q
   while (Number != 'Q' & Number != 'q');
}

}

感谢大家的回复。我有点新,所以 try 语句对我来说是新的,但看起来它会起作用(似乎有点自我解释它的作用)。我会更多地研究它的使用并正确地实现它。

【问题讨论】:

标签: java


【解决方案1】:

我会使用nextLine()parseInt() 来查看它是否是int

    int Number;
    String test = "";
    boolean isNumber = false;
    ......

    test = Input.nextLine();
    try
    {
        Number = Integer.parseInt(test);
        isNumber = true;
    }
    catch(NumberFormatException e)
    {
         isNumber = false;
    }
    if(isNumber)
    {
        if (Number >= 1 && Number <= 10)
        {
            System.out.println("Your number is between 1 and 10");
        }   
        else
        {
            System.out.println("Error: The number you have entered is not between"
                + " 1 and 10, try again");
        }
    }
    else
    {
        if (test.equalsIgnoreCase("q"))
        {
            System.out.println("You are now exiting the program");
        }
    }

.........
while (!test.equalsIgnoreCase("q"));

【讨论】:

  • catch 语句总是有 e 吗?这是我唯一有点模糊的事情。我理解那里的所有其他内容,但 e 让我有点失望,它只是语法的一部分吗?
  • e 可以是任何东西...它可以是catch(NumberFormatException ex) 它可以是catch(NumberFormatException exception) 它可以是catch(NumberFormatException anything)。它只是您传递给catch 块的变量。在catch 块内,它将保存与引发的异常相关的信息,例如StackTrace
  • 为了澄清上述注释,“e”是该异常实例的变量名。然后,如果需要,您可以对异常实例进行处理(例如,e.getStackTrace)。该名称与您的目的无关。
  • 站起​​来,至少说出原因。如果您要对正确答案投反对票,那么您真的不应该这样做。
【解决方案2】:

试试这个

    Scanner Input = new Scanner(System.in);
    //Initialize Number as 0 to reset while loop
    String Number = "0";

    do {
        try {
            //Ask user to input a number between 1 and 10
            System.out.println("At anytime please press 'q' to quit the program.");
            System.out.println();
            System.out.print("Please enter a number between 1 and 10:");
            Number = Input.next();

            if (Number.equalsIgnoreCase("q")) {
                System.out.println("You are now exiting the program");
            } else if (Integer.valueOf(Number) >= 1 && Integer.valueOf(Number) <= 10) {
                System.out.println("Your number is " + Number);
            } else {
                System.out.println("Error: The (" + Number + ") is not between 1 and 10, try again");
            }
        } catch (NumberFormatException ne) {
            System.out.println("Error: The (" + Number + ") is not between 1 and 10, try again");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    } //Continue the loop while Number is not equal to Q
    while (!Number.equalsIgnoreCase("q"));

【讨论】:

    【解决方案3】:

    将您的输入作为字符串读入,以检查 Q/q 的输入。然后,您可以通过以下方式将输入字符串从输入字符串解析为整数,捕获潜在的 NumberFormatExceptions。

    String input = "5"
    try {
    int number = Integer.parseInt(input);
    } catch (NumberFormatException e) {
    System.out.println("Not a number!") 
    }
    

    或类似的东西。

    【讨论】:

      【解决方案4】:

      您可以通过这种方式检查它是否为int

      String inputArg = Input.next();
      
      private boolean isInt(String inputArg){
          boolean isInt = true;
          try {
               Integer.parseInt(inputArg);
          } catch(NumberFormatException e) {
               isInt = false;
          }
          return isInt;
      }
      

      其他方式是使用regular expressions

      【讨论】:

        【解决方案5】:

        找到这段代码检查一下,它对我有用。

                  Scanner input = new Scanner (System.in);
                  if (input.hasNextInt()) {
                      int a = input.nextInt();
                      System.out.println("This input is of type Integer."+a);
                  }   
                           
                  else if (input.hasNextLong())
                    System.out.println("This input is of type Long.");
               
                  else if (input.hasNextFloat())
                  System.out.println("This input is of type Float.");
                  
                  else if (input.hasNextDouble()) 
                  System.out.println("This input is of type Double."); 
                   
                  else if (input.hasNextBoolean())
                   System.out.println("This input is of type Boolean.");  
                  
                  else if (input.hasNextLine())
                      System.out.println("This input is of type string."); 
        
        

        【讨论】:

          【解决方案6】:

          您可以将输入作为字符串获取,然后对所述字符串使用正则表达式匹配。

          String txt = Input.nextLine();
          if(txt.matches("[0-9]+") // We have a number
          {
             // Safe to parse to number
          }
          else if(txt.matches("[A-Za-z]+") // We have alphabeticals
          {
             // Check for various characters and act accordingly (here 'q')
          }
          

          【讨论】:

          • 在这种情况下不需要使用正则表达式,这会使解决方案过于复杂。
          • 我将不得不不同意你的观点。我认为它根本不会增加太多复杂性,用途更广泛,并且不依赖于程序流的异常处理。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-23
          • 2011-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多