用户输入字符串而不是整数输入时捕获错误

时间:2018-11-01 12:26:27

标签: java

我希望代码在用户输入字符串而不是整数时捕获错误。您可以看到我尝试了一个try catch块,但仍然无法正常工作。除此之外,其他一切都很完美。我该怎么解决?

输出内容如下:

import datetime as dt
from sklearn import linear_model

df = pd.DataFrame(list, columns=['date', 'value'])
df['date_ordinal'] = pd.to_datetime(df['date']).map(dt.datetime.toordinal)
reg = linear_model.LinearRegression()
reg.fit(df['date_ordinal'].values.reshape(-1, 1), df['value'].values)

reg.coef_

array([0.80959405])

代码如下:

Welcome to the Squares and Cubes table

Enter an integer: five
Error! Invalid integer. Try again.
Enter an integer: -5
Error! Number must be greater than 0
Enter an integer: 101
Error! Number must be less than or equal to 100
Enter an integer: 9

Number  Squared Cubed
======  ======= =====
1       1       1
2       4       8
3       9       27
4       16      64
5       25      125
6       36      216
7       49      343
8       64      512
9       81      729

Continue? (y/n): y

Enter an integer: 3

Number  Squared Cubed
======  ======= =====
1       1       1
2       4       8
3       9       27

4 个答案:

答案 0 :(得分:1)

为了避免引起混淆,我对您的代码做了一些更改并将其整体发布了:

public static void main(String[] args) {
    // Welcome the user
    System.out.println("Welcome to the Squares and Cubes table");
    System.out.println();
    Scanner sc = new Scanner(System.in);
    String choice = "y";

    do {
        int integer = Integer.MAX_VALUE;
        while (integer == Integer.MAX_VALUE) {
            // Get input from the user
            System.out.print("Enter an integer: ");
            String input = sc.nextLine();
            try {
                integer = Integer.parseInt(input);
            }
            catch (NumberFormatException e) {
                System.out.println("Error! Invalid integer. Try again.");
            }
        }
        if(integer<0){

            System.out.println("Error! Number must be greater than 0");
            System.out.print("Enter an integer: ");
            integer = sc.nextInt();

        }

        if(integer>100){

            System.out.println("Error! Number must be less than or equal to 100");

            System.out.print("Enter an integer: ");
            integer = sc.nextInt();
        }

        // Create a header
        String header = "Number  " + "Squared " + "Cubed   " + "\n"
                +   "======  " + "======= " + "=====   ";
        System.out.println(header);

        int square = 0;
        int cube = 0;

        String row = "";
        for (int i = 1; i <= integer; i++)
        {

            square = i * i;
            cube = i * i * i;

            row = i + "       " + square + "       " + cube;
            System.out.println(row);
        }

        // See if the user wants to continue
        System.out.print("Continue? (y/n): ");
        choice = sc.next();
        System.out.println();

    } while (!choice.equalsIgnoreCase("n"));
}

这个想法是在循环中创建另一个while并运行它,直到用户传递整数为止。

答案 1 :(得分:0)

Integer.parseInt方法是将String转换为int类型,如果无法将字符串转换为NumberFormatException类型则抛出int

应该是这样的:

    System.out.print("Enter an integer: ");
    Scanner sc =new Scanner(System.in);

    try {
        int integer = Integer.parseInt(sc.nextLine());
    } catch (NumberFormatException e) {
        System.out.println("Error! Invalid integer. Try again.");
    }

答案 2 :(得分:0)

您可以使用此方法仅测试输入的值是否为有效整数。根据此结果,您可以从其他验证开始

public boolean isInt(string input) {
    try {
      Integer.parseInt(text);
      return true;
    } catch (NumberFormatException e) {
     return false;
     } 
    }

答案 3 :(得分:-2)

使用此getInput(scanner);方法来获取用户的输入。这将处理异常并递归调用自身,直到用户输入数字为止。

public static int getInput(Scanner sc) {
    int integer=0;
    try {
        System.out.print("Enter an integer: ");

        integer = Integer.parseInt(sc.nextLine());
    }       
    catch (Exception e) {
        System.out.println("Error! Invalid integer. Try again.");
        getInput( sc);
    }

    return integer;
}

对该函数的调用将类似于int integer = getInput(sc);

修改后,您的代码将如下所示,

public class cube2 {

    public static int getInput(Scanner sc) {
        int integer=0;
        try {
            System.out.print("Enter an integer: ");

            integer = Integer.parseInt(sc.nextLine());
        }       
        catch (Exception e) {
            System.out.println("Error! Invalid integer. Try again.");
            getInput( sc);
        }

        return integer;
    }

    public static void main(String[] args)
    {
        // Welcome the user
        System.out.println("Welcome to the Squares and Cubes table");
        System.out.println();

        Scanner sc = new Scanner(System.in);
        String choice = "y";

        do
        {


            int integer = getInput(sc); // To get the Numeric input from Console

            if(integer<0){

                System.out.println("Error! Number must be greater than 0");
                System.out.print("Enter an integer: ");
                integer = sc.nextInt();

            }

            if(integer>100){

                System.out.println("Error! Number must be less than or equal to 100");

                System.out.print("Enter an integer: ");
                integer = sc.nextInt();
            }

            // Create a header
            String header = "Number  " + "Squared " + "Cubed   " + "\n"
                    +   "======  " + "======= " + "=====   ";
            System.out.println(header);

            int square = 0;
            int cube = 0;

            String row = "";
            for (int i = 1; i <= integer; i++)
            {

                square = i * i;
                cube = i * i * i;

                row = i + "       " + square + "       " + cube;
                System.out.println(row);
            }

            // See if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.nextLine();
            System.out.println();

        }
        while (!choice.equalsIgnoreCase("n"));  
    }
}

在您的代码中choice = sc.next();更改为choice = sc.nextLine();

输出:

Welcome to the Squares and Cubes table

Enter an integer: 9
Number  Squared Cubed   
======  ======= =====   
1       1       1
2       4       8
3       9       27
4       16       64
5       25       125
6       36       216
7       49       343
8       64       512
9       81       729
Continue? (y/n): y

Enter an integer: hi
Error! Invalid integer. Try again.
Enter an integer: hello
Error! Invalid integer. Try again.
Enter an integer: 5
Number  Squared Cubed   
======  ======= =====   
Continue? (y/n): y

Enter an integer: 12
Number  Squared Cubed   
======  ======= =====   
1       1       1
2       4       8
3       9       27
4       16       64
5       25       125
6       36       216
7       49       343
8       64       512
9       81       729
10       100       1000
11       121       1331
12       144       1728
Continue? (y/n):