使用 try catch 检查整数输入是否为字符串

checking if an input of an integer is a string with try catch

我希望 try-catch 循环直到我输入一个正确的整数,但是当我输入一个字符串时,我所拥有的只是一个无限循环:

public class Main00 {
static Scanner scan = new Scanner(System.in);
static int c = 1;

public static void main(String[] args) {
    int num = 0;
    while (c == 1) {
        try {
            System.out.println("enter a number");
            num = scan.nextInt();
            c = 2;
        } catch (Exception e) {
            System.out.println("enter a Number please : ");
        }
    }

试试

try {
        System.out.println("enter a number");
        num = scan.nextInt();
        c = 2;
    } catch (Exception e) {
        c = -1;
        System.out.println("best of luck next time :)");
}

将循环替换为以下内容:

while (c == 1) {
            try {
                System.out.println("enter a number");
                num = Integer.parseInt(scan.nextLine());
                c=2;
            } catch (Exception e) {
                System.out.println("enter a Number please : ");
            }
        }

试试这个

public class Main00 {
static Scanner scan = new Scanner(System.in);
static int c = 1;

public static void main(String[] args) {
int num = 0;
while (c == 1) {
    try {
        System.out.println("enter a number");
        String value = scan.nextLine();
        num = Integer.parseInt(value);
        c=2;
        break;
    } catch (Exception e) {
        continue;
    }
}

使用最少的变量和更整洁,你真的不需要 c 变量。

    int num = 0;
    Scanner scan = new Scanner(System.in);
    while (true) {
        try {
            System.out.println("Enter a number");
            num = Integer.parseInt(scan.next());
            break;
        } catch (Exception e) {
            continue;
        }
    }

这是我的解决方案,没有使用异常来验证输入和一些其他优化:

public static void main(String[] args) {
    int num;
    while (true) {
        System.out.println("enter a valid number");
        if(scan.hasNextInt()){
            num = scan.nextInt();
            break;
        }else{
            scan.next();
        }
    }
    System.out.println("input: " + num);
}

您只需检查下一个值是否为整数,如果是整数,则直接将其放入您的 num 值中。这具有不使用异常且不需要将 String 解析为整数的好处。我还更改了 while 循环,现在您不需要那个 c 变量...这只是令人困惑 ;-)