Java 只让用户输入正整数(没有小数或字符串)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18804872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:13:30  来源:igfitidea点击:

Only let users input positive integers (no decimals or strings)?

javastringinputinteger

提问by Jake

I know how to ask the user to input positive integers, but I don't know how approach the code to avoid an input error such as a decimal or string input.

我知道如何要求用户输入正整数,但我不知道如何处理代码以避免输入错误,例如十进制或字符串输入。

  int seedValue;
  double angle, gunpowder;

  System.out.println("Please enter a positive integer seed value: ");
  seedValue = input.nextInt();

     while (seedValue <= 0) {  
        System.out.println("Please enter a positive integer seed value: ");
        seedValue = input.nextInt();
     }

     System.out.println("That target is " +
      threeDec.format(gen.nextDouble() * 1000) + "m away.");

采纳答案by Juned Ahsan

This may be an approch:

这可能是一种方法:

  • Read the input as a stringvalue using Scanner.readLine();
  • Try to convert the string to int using Integer.parseIntmethod. This method will throw a NumberFormatExceptionin case the input string contains decimals and invalid digits.
  • if the input value is parsed properly in previous step, then check for negative
  • 读取输入的string应用价值Scanner.readLine();
  • 尝试使用Integer.parseInt方法将字符串转换为 int 。NumberFormatException如果输入字符串包含小数和无效数字,此方法将抛出 a 。
  • 如果在上一步中正确解析了输入值,则检查是否为负

回答by Scott Shipp

I am assuming that "input" is the Scanner class. If so, check out the javadoc for the Scanner.nextInt() method. It throws a number of exceptions if an integer is not entered. So you should put your call to it in a try catch block and look for these exceptions. The next thing you can do since that still lets them enter a negative value is simply check if the input is less than 0 and if so, output some message letting the user know they must only enter a positive value.

我假设“输入”是 Scanner 类。如果是这样,请查看 Scanner.nextInt() 方法的 javadoc。如果没有输入整数,它会抛出许多异常。因此,您应该将调用放在 try catch 块中并查找这些异常。由于这仍然让他们输入负值,因此您可以做的下一件事就是检查输入是否小于 0,如果是,则输出一些消息,让用户知道他们只能输入正值。

回答by Thirumalai Parthasarathi

System.out.println("Please enter a positive integer seed value: ");
boolean flag = true;
while(flag) {
  try {
    seedValue = Integer.valueOf(input.nextLine());
    if (seedValue <= 0) {
      System.out.println("input is not a positive Integer ");
      System.out.println("Please enter a positive integer seed value: ");
    } else {
      flag=false;
    }
  } catch(NumberFormatException e) {
      System.out.println("input is not a positive Integer ");
      System.out.println("Please enter a positive integer seed value: ");
  }

}

回答by Philipp Seeger

Your attempt looks fine, you let the user type something in and then check if it matches the required form. If not, proceed in asking the user again or output an error or whatever. If you want to make the program in a way, that letters, like the '-' char don't even appear on the screen while typing in, you still have to read whatever the user typed in, validate it, reform the string (delete the illegal letter) and refresh the screen with every single keystroke happening. This is probably not what should be done here.

您的尝试看起来不错,您让用户输入一些内容,然后检查它是否与所需的表单匹配。如果没有,继续询问用户或输出错误或其他什么。如果你想以某种方式制作程序,像“-”这样的字母在输入时甚至不会出现在屏幕上,你仍然需要阅读用户输入的任何内容,验证它,重新修改字符串(删除非法字母)并在每次击键时刷新屏幕。这可能不是这里应该做的。

Imagine your common social websites while creating a profile with password requirements like having one number, at least 6 letters and so on. You can type whatever you want in the textbox, only after submitting the form the program either accepts your input or redirects you to the same form with an error message to hint at the problem.

想象一下您的常见社交网站,同时创建具有密码要求的个人资料,例如具有一个数字、至少 6 个字母等。您可以在文本框中输入您想要的任何内容,只有在提交表单后,程序才会接受您的输入或将您重定向到同一表单并显示错误消息以提示问题。

回答by David says Reinstate Monica

Im not sure what class inputis exactly, but I presume its Scannerreading from standard in. If this is the case, you can take advantage of the exceptions thrown by nextInt(), specifically InputMismatchException. Your code would be -

我不确定到底input是什么类,但我认为它是Scanner从标准中读取的。如果是这种情况,您可以利用 抛出的异常nextInt(),特别是InputMismatchException. 你的代码是 -

int seedValue;
double angle, gunpowder;

System.out.println("Please enter a positive integer seed value: ");
while(invalidInput){
   try{
     seedValue = input.nextInt();
     if(seedValue <= 0) {  
            System.out.println("Please enter a positive integer seed value: ");
     }
     else{invalidInput=false;}
   }
   catch(InputMismatchException e){
        System.out.println("Please enter a positive integer seed value: ");
   }

}

}

     System.out.println("That target is " +
      threeDec.format(gen.nextDouble() * 1000) + "m away.");