有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java请求一个整数

我试图解决下一个任务: 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");
}

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

我将非常感谢你的帮助


共 (3) 个答案

  1. # 1 楼答案

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

    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的文章

  2. # 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.");
            }
          }
        }
    }
    
  3. # 3 楼答案

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

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