开发者

Nested Loops Won't Work In Java Program

I am writing this program using try-catch exception handling:

    Scanner keyboard = new Scanner(System.in);
    String[] employees = new String[5];
    boolean done1 = false;

    //input and error exception for entering employee names into an array
    for (int i = 0; i < 5; i++)
    {//begin for

        while (!done1)
        {//begin while

            System.out.println("Please enter employee's name: ");
            try
            {//begin try
                employees[i] = keyboard.nextLine();

                if (employees[i].length() == 0)
                    throw new Exception("No name was entered.");

                if (employees[i].length() >= 3开发者_如何学JAVA1)
                    throw new Exception("Name entered contains too many "
                            + "characters");

                for (int check = 0; check < employees[i].length(); check++)
                {//begin for
                    if(Character.isDigit(employees[i].charAt(check)))
                        throw new Exception("Input contains invalid "
                                + "charaters.");
                }//end for

                done1 = true;
            }//end try

            catch (Exception a)
            {//begin catch
                System.out.println("Error: " + a.getMessage());
            }//end catch

        }//end while

    }//end for

When I run the program, it kicks out of the for loop and only inputs that first instance of i and the rest are left null. How can I get the program to stay in this loop and have it keep the error checking?


Your done1 variable remains true after the first loop, causing subsequent while statements to not enter the loop body.

It is probably better to eliminate the done1 variable entirely, and use a structure like this:

for (...) {
    while (true) {
        try {
            // get user input
            break;
        } catch (Exception e) {
            // ..
        }
    }
}


Set done1 back to false. Or insert done1 = false as the first line in the main for cycle.


It might be easiest to simply put another try catch block within your for loop. When the exception is thrown, it will use the for loop's catch and continue iterating.

Something like this:

for (int check = 0; check < employees[i].length(); check++)
            {//begin for
                try {
                    if(Character.isDigit(employees[i].charAt(check)))
                        throw new Exception("Input contains invalid "
                                + "charaters.");
                }
                catch(Exception e)
                { //Handle Error
                }
            }//end for


the first time you enter the while loop the !done1 expressions evaluates to true since done1 is false. toward the end you set done1 to true. when you evaluate !done1 in order to perform the loop again, the expression is now false since you set done1 to true in the first pass.


You are not using Exceptions correctly...

Exceptions are a very expensive way of handling logic like this, and your approach in just creating a none specific exception and using it is wrong. Exceptions are designed for dealing with exceptional things that might happen in your programs - resource unavailablility, connection timeouts - that sort of thing.

The problem you are looking at should be approached with mere flow control.

Hope this helps...

Martin.

Ps. Your code, with the Exceptions replaced by something a little more reasonable, might look like this:

import java.util.Scanner;
public class SOExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        String[] employees = new String[5];
        boolean done1 = false;
        String strMessage = "";
        //input and error exception for entering employee names into an array
        for (int i = 0; i < 5; i++)
        {//begin for
            done1 = false;

            while (!done1)
            {//begin while
                strMessage="";
                System.out.println("Please enter employee's name: ");
                employees[i] = keyboard.nextLine();

                if (employees[i].length() == 0)
                    strMessage = "No name was entered.";

                if (employees[i].length() >= 31)
                    strMessage = "Name entered contains too many "
                            + "characters";
                if (strMessage == ""){
                    for (int check = 0; check < employees[i].length(); check++)
                    {//begin for
                        if(Character.isDigit(employees[i].charAt(check))){
                            strMessage = "Input contains invalid "
                                    + "charaters.";
                            break;
                        }
                    }//end for
                }

                done1 = (strMessage == "");
                if (!done1){
                    System.out.println("Error: " + strMessage);
                }

            }//end while

        }//end for

    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜