简体   繁体   English

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

[英]Catching error when a user enters a string instead of an integer input

I would like the code to catch the error when the user enters a string instead of an integer. 我希望代码在用户输入字符串而不是整数时捕获错误。 You can see I have tried a try catch block which is still not working. 您可以看到我尝试了一个try catch块,但仍然无法正常工作。 Everything else is perfect apart from that. 除此之外,其他一切都很完美。 How can I solve this? 我该如何解决?

Here is how the output should be: 输出结果如下:

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

Here is the code: 这是代码:

import java.util.InputMismatchException;
import java.util.Scanner;

public class cube2 {

    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
        {
            // Get input from the user
            System.out.print("Enter an integer: ");
            int integer = sc.nextInt();


                 try {

                    break;
                }
                catch (NumberFormatException e) {
                    System.out.println("Error! Invalid integer. Try again.");
                }



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





             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"));  
    }
}

I changed your code a little bit and posted it as a whole, to avoid confusion: 为了避免混淆,我对您的代码做了一些更改并将其整体发布了:

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"));
}

The idea was to make another while inside your loop and run it until a user passes an integer. 这个想法是让您在循环内进行另一个操作while直到用户传递整数为止。

Integer.parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type. Integer.parseInt方法是将String转换为int,如果无法将字符串转换为int类型,则引发NumberFormatException

It should be like this: 应该是这样的:

    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.");
    }

You could use this method just to test if the entered value is a valid integer. 您可以使用此方法来测试输入的值是否为有效整数。 Base the outcome of this you can start with your other validation 根据此结果,您可以从其他验证开始

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

Use this getInput(scanner); 使用此getInput(scanner); method to get the input from user. 从用户获取输入的方法。 This will handle the exception and recursively calls itself till the user enters the number. 这将处理异常并递归调用自身,直到用户输入数字为止。

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;
}

Call to this function will be like int integer = getInput(sc); 对该函数的调用将类似于int integer = getInput(sc);

After this modification, your code will looks like, 修改之后,您的代码将如下所示:

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"));  
    }
}

In your code choice = sc.next(); 在您的代码中choice = sc.next(); was changed in to choice = sc.nextLine(); 更改为choice = sc.nextLine();

Output : 输出:

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): 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM