【问题标题】:How to insist that a users input is an int?如何坚持用户输入是int?
【发布时间】:2012-10-29 02:43:26
【问题描述】:

这里的基本问题.. 我将首先要求您不要回复任何代码,因为这可能只会让我更加困惑(编程菜鸟)。我正在寻找关于如何解决我遇到的这个问题的明确解释。

我有一个读取用户输入的扫描仪。提示用户输入 1 到 150 之间的 int 值(仅限整数)。我得到的值如下:

    Scanner scan = new Scanner(System.in);
    int input = scan.nextInt();

继续我的程序,一切正常。

不幸的是,代码并不完全是防弹的,因为任何不是整数的输入都可能破坏它(字母、符号等)。

如何使代码更健壮,以验证是否只输入了一个 int?

这些是我希望的结果:

假设输入是:

23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc

【问题讨论】:

    标签: java input int java.util.scanner


    【解决方案1】:

    我写了一个例子,确保程序只有在输入数字而不是无效值时才会继续。别担心,我添加了想要的解释。

    程序要求用户输入一个数字。循环确保在输入有效数字之前不会继续处理。在此之前,我定义了一个默认值为 false 的变量“inputAccepted”。如果他输入一个数字,则变量“inputAccepted”设置为真,程序退出循环。但是如果他输入的不是数字,此时就会抛出异常,并且将变量“inputAccepted”设置为true的行将不会被执行。相反,将打印一条消息,告诉用户他的输入无效。由于 "inputAccepted" 不能设置为 true,循环将再次执行相同的操作,直到可以将字符串转换为数字。

    You can test the program here.

    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            boolean inputAccepted = false;
            while (!inputAccepted) {
                try {
                    System.out.print("Please enter a number: ");
                    Integer.valueOf(input.nextLine());
                    inputAccepted = true;
                } catch (NumberFormatException e) {
                    System.out.println("Not a valid number.");
                }
            }
            System.out.println("Thank you!");
        }
    }
    

    【讨论】:

      【解决方案2】:

      Scanner.hasNextInt() 如果下一个标记是数字则返回true,否则返回false

      在本例中,我调用 hasNextInt()。如果它返回true,我会过去一段时间并设置输入;如果它返回false,那么我丢弃输入(scanner.next();)并重复。

      Scanner scan = new Scanner(System.in);
      while(!scan.hasNextInt()) {
          scan.next();
      }
      int input = scan.nextInt();
      

      【讨论】:

      • -1 如果用户输入非整数,您的代码将挂起并且永远不会恢复:scanner.hasNextInt() 不会推进过去的输入,如果下一个输入是非整数,scanner.hasNextInt()将始终返回 false,即使用户稍后输入整数
      • @Bohemian:是的,谢谢,我已更正代码以丢弃非 int 输入。
      • 我认为您的意思是在 while 循环中编写扫描,而不是扫描仪(两次),否则,谢谢!
      【解决方案3】:

      只要得到“任何东西”并解析它:

      Scanner scan = new Scanner(System.in);
      
      Integer number = null;
      while (number == null) {
          try {
              number = Integer.parseInt(scan.next());
          } catch (NumberParseException e) {
              System.out.println("bad input: " + input);
          }
      }
      

      【讨论】:

        【解决方案4】:

        这是一个带有提示和 cmets 的简单示例。

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter an integer: "); // Initial prompt for input
        
        // Repeat until next item is an integer
        while (!scan.hasNextInt()) 
        {        
            scan.next(); // Read and discard offending non-int input
            System.out.print("Please enter an integer: "); // Re-prompt
        }
        
        // At this point in the code, the user has entered an integer
        int input = scan.nextInt(); // Get the integer
        
        // And now you can use the input variable.
        

        【讨论】:

          【解决方案5】:

          使用scan.hasNextInt() 确保下一个输入是int

          【讨论】:

          • 如果用户输入一个非整数,你的代码将挂起并且永远不会恢复:scanner.hasNextInt() 不会推进过去的输入,如果下一个输入是非整数,scanner.hasNextInt() 将始终返回 false,即使用户稍后输入整数
          • @Bohemian 我没有给出任何建议如何使用它,你只是从 ignis 复制的...
          【解决方案6】:

          没有任何代码,只有英文,我想说有两件事你必须测试或注意。首先输入是 int,其次 int 在正确的范围内。

          就伪代码而言,首先要做的是确保它是一个 int。声明一个名为“input”的 int,我会放置一个 try/catch 块,您可以在其中尝试使用 parseInt() 将用户输入扫描为 int。如果 try 部分失败,您知道它不是 int 并且可以返回错误消息。

          那么,既然你知道“input”是一个int,你可以测试它是小于1还是大于150,如果是则返回错误信息!

          【讨论】:

            【解决方案7】:

            公共类示例{

            /**
             * author CLRZ
             */
            public static void main(String[] args) {
                int a; // variable
                Scanner in = new Scanner(System.in); // scans your input
                System.out.println("Enter your number's choice:"); 
                int sem1 = in.nextInt(); // reads next integer
                if (sem1 == 1) // conditioned if your choice number is equal to 1
                System.out.println("Hello World1"); // output wil be Hello World
                int b;
            
                System.out.println("Enter your number's choice:");
                int sem2 = in.nextInt(); 
                if (sem2 == 2)
                System.out.println("Hello World2");
                int c;
            
                System.out.println("Enter your number's choice:");
                int sem3 = in.nextInt(); 
                if (sem3 == 3)
                System.out.println("Hello World3");
            }
            

            }

            【讨论】:

            • OP 要求提供非代码解释。此外,这段代码没有处理任何异常。
            猜你喜欢
            • 2023-03-22
            • 2020-06-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-05-25
            • 1970-01-01
            相关资源
            最近更新 更多