简体   繁体   中英

Using Try/Catch in JAVA

I have the following piece of code where I'm trying to get the user to only enter integers; if a string is entered then it would display a system out error message "please only enter numbers" and then it would show the "Enter your ID#:" again. I tried using the try/catch method but was not using it correctly -- still a beginner. I know I can use the " NumberFormatException " but not sure where. Can anyone help? Thanks!

        //Get Customer ID and Account Number
        do
        {   System.out.print("Enter your ID#: ");
            custid = Integer.parseInt(input.readLine());
            System.out.print("Enter your Account Number#: ");
            custacctnum = Integer.parseInt(input.readLine());
        //validate the choice
            for(int i=0; i<people.length; i++)  
            {   if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
                {   match = true;
                System.out.println("Welcome "  +people[i].firstname+ " to JJ Dealership!");
                for(int p=0; p<cluster.length; p++)
                    System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);

                System.out.println(people[i].firstname+ ", what color car would you like?");
                    break;
                }
            }
            if (!match)
            {   System.out.println("Invalid ID");   
        } while (!(match));

Exceptions should be for exceptional circumstances. I suggest you use a Scanner and hasNextInt() to just continue when it isn't an int . That is make a Scanner like,

Scanner input = new Scanner(System.in);

and then something like this would work,

do {
    System.out.print("Enter your ID#: ");
    if (!input.hasNextInt()) {
        System.out.printf("%s is not an int.%n", input.nextLine());
        continue;
    }
    custid = input.nextInt();
    System.out.print("Enter your Account Number#: ");
    custacctnum = input.nextInt();
    if (!input.hasNextInt()) {
        System.out.printf("%s is not an int.%n", input.nextLine());
        continue;
    }

If you really want to use try-catch it should look something like,

do
{
    try {
        System.out.print("Enter your ID#: ");
        custid = Integer.parseInt(input.readLine());
        System.out.print("Enter your Account Number#: ");
        custacctnum = Integer.parseInt(input.readLine());
    //validate the choice
        for(int i=0; i<people.length; i++)  
        {   if ((people[i].custid == custid) &&
                    (people[i].custacctnum == custacctnum))
            {   match = true;
            System.out.println("Welcome "  +people[i].firstname
                    + " to JJ Dealership!");
            for(int p=0; p<cluster.length; p++)
                System.out.println("" + (p+1) + ": " +cluster[p].year+","
                        + cluster[p].make+ "," +cluster[p].model);

            System.out.println(people[i].firstname
                     + ", what color car would you like?");
                break;
            }
        }
    } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
    }
} while (!(match));

@Elliott Frisch, I "played" around with it before I saw your answer and figured out how to use the try/catch. It was fairly simple, but I will look at the other option that you posted. With the updated code below when the user enters a string, it will display the error message and then take them to the "Enter your ID#" line to try again.

Thank you all so much for the quick response.

do
        {   
            try{
                System.out.print("Enter your ID#: ");
                custid = Integer.parseInt(input.readLine());
                System.out.print("Enter your Account Number#: ");
                custacctnum = Integer.parseInt(input.readLine());
        //validate the choice
            for(int i=0; i<people.length; i++)  
            {   if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
                {   match = true;
                System.out.println("Welcome "  +people[i].firstname+ " to JJ Dealership!");
                for(int p=0; p<cluster.length; p++)
                    System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);

                System.out.println(people[i].firstname+ ", what color car would you like?");
                    break;
                }
                }
                    if (!match)
                    {   System.out.println("Invalid ID");   
            }
            } catch (NumberFormatException e)
            {System.out.println ("Error! Please enter a number!");}
            } while (!(match));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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