簡體   English   中英

用戶輸入字符串而不是整數輸入時捕獲錯誤

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

我希望代碼在用戶輸入字符串而不是整數時捕獲錯誤。 您可以看到我嘗試了一個try catch塊,但仍然無法正常工作。 除此之外,其他一切都很完美。 我該如何解決?

輸出結果如下:

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

這是代碼:

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

為了避免混淆,我對您的代碼做了一些更改並將其整體發布了:

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直到用戶傳遞整數為止。

Integer.parseInt方法是將String轉換為int,如果無法將字符串轉換為int類型,則引發NumberFormatException

應該是這樣的:

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

您可以使用此方法來測試輸入的值是否為有效整數。 根據此結果,您可以從其他驗證開始

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

使用此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): 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM