【问题标题】:How do I prevent program from terminating when user inputs a string when the program expects an integer?当程序需要整数时,如何防止程序在用户输入字符串时终止?
【发布时间】:2014-02-16 23:03:53
【问题描述】:

我正在尝试设置一个 do-while 循环,该循环将重新提示用户输入,直到他们输入一个大于零的整数。我不能为此使用 try-catch;这是不允许的。这是我得到的:

Scanner scnr = new Scanner(System.in);
int num;
do{
System.out.println("Enter a number (int): ");
num = scnr.nextInt();
} while(num<0 || !scnr.hasNextLine());

如果输入负数则循环,如果是字母则程序终止。

【问题讨论】:

  • 我们的答案对您有帮助吗?
  • 这是一个入门级的项目(所以我不能用try-catch——因为我们没学过),不知道能不能用解析整数()。这对我来说很有意义,我现在将尝试实现它。谢谢,伙计们。
  • 如果你不能使用 try-catch 并且你不能使用 string regex/parseInt 那么你在做一个荒谬的项目。

标签: java exception exception-handling java.util.scanner do-while


【解决方案1】:

你可以把它当作一个字符串,然后用正则表达式来测试这个字符串是否只包含数字。因此,如果它实际上是一个整数,则只分配字符串的整数值num。这意味着您需要将num 初始化为-1,这样如果它不是整数,则while 条件为真,它会重新开始。

Scanner scnr = new Scanner(System.in);
int num = -1;
String s;
do {
    System.out.println("Enter a number (int): ");
    s = scnr.next().trim(); // trim so that numbers with whitespace are valid

    if (s.matches("\\d+")) { // if the string contains only numbers 0-9
        num = Integer.parseInt(s);
    }
} while(num < 0 || !scnr.hasNextLine());

示例运行:

Enter a number (int): 
-5
Enter a number (int): 
fdshgdf
Enter a number (int): 
5.5
Enter a number (int): 
5

【讨论】:

    【解决方案2】:

    由于不允许使用 try-catch,请改为调用 nextLine()
    nextInt(),然后测试你自己是否得到了String
    back 是否为整数。

    import java.util.Scanner;
    
    public class Test038 {
    
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            int num = -1;
            do {
                System.out.println("Enter a number (int): ");
                String str = scnr.nextLine().trim();
                if (str.matches("\\d+")) {
                    num = Integer.parseInt(str);
                    break;
                }
    
            } while (num < 0 || !scnr.hasNextLine());
            System.out.println("You entered: " + num);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 2012-04-29
      • 2012-06-01
      相关资源
      最近更新 更多