【问题标题】:Asking for an integer [closed]要求一个整数[关闭]
【发布时间】:2020-06-17 17:41:43
【问题描述】:

我尝试解决下一个任务: 1. 向用户询问一个正整数。 2. 如果用户添加负数或实数或两者都添加,控制台上应显示下一条错误消息:“输入错误”。

这就是我到目前为止所做的。

Scanner sc = new Scanner(System.in);
System.out.print("Please, add a positive integer! ");
int num = sc.nextInt();
if (num < 0) {
    System.out.println("wrong input");
}

一切正常,但如果用户输入的不是整数而是实数,我无法确保他/她会收到错误消息。在这种情况下,程序出错了。

我将不胜感激。

【问题讨论】:

标签: java if-statement integer


【解决方案1】:

当您使用Scanner.nextInt() 时,输入应为整数。输入任何其他内容,包括实数,都会抛出InputMismatchException。为确保无效输入不会停止您的程序,请使用 try/catch 处理异常:

int num;
try {
    num = sc.nextInt();
    // Continue doing things with num
} catch (InputMismatchException e) {
    // Tell the user the error occured
}

【讨论】:

  • 谢谢。我还没遇到try catch。
【解决方案2】:
import java.util.Scanner;
import java.util.InputMismatchException;

public class ScanTest
{
  public static void main(String[] args)
  {
    Scanner sc = new Scanner(System.in);
    boolean badInput = true;
    int num;

    // Keep asking for input in a loop until valid input is received

    while(badInput)
    {
        System.out.print("Please, add a positive integer! ");

        try {
            num = Integer.parseInt(sc.nextLine());
            // the try catch means that nothing below this line will run if the exception is encountered
            // control flow will move immediately to the catch block
            if (num < 0) {
                System.out.println("Please input a positive value.");
            } else {
                // The input is good, so we can set a flag that allows us to exit the loop
                badInput = false;
            }
        }
        catch(InputMismatchException e) {
            System.out.println("Please input an integer.");
        }
        catch(NumberFormatException e) {
          System.out.println("Please input an integer.");
        }
      }
    }
}

【讨论】:

  • 谢谢。现在,我了解了 try catch 的工作原理。
【解决方案3】:

有时我发现读取一个字符串然后尝试解析它更容易。这假定您希望重复提示,直到获得有效号码。

Scanner sc = new Scanner(System.in);
int num = -1;
while (num < 0) {
    System.out.print("Please, add a positive integer! ");

    String str = sc.nextLine();
    try {
        num = Integer.parseInt(str);
    } catch (NumberFormatException e) {
         System.out.println("Only integers are accepted.");
         continue;
    }
    if (num < 0) {
        System.out.println("Input is < 0.");
    }
}

在此处了解NumberFormatException

【讨论】:

  • 谢谢!整数解对我来说是新的。
  • 不客气!
猜你喜欢
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
相关资源
最近更新 更多