开发者

infinite for loop...?

I've built this program to read a user name from a file. It checks to see if the user name that the user entered is on the profile file. Now, if it isn't on the file, it asks would you like to create a new user? What I'm trying to do is some input validation from the user - meaning, I want him to be able to answer with only a Y for yes and N for no, and for only 5 attempts.

My problem is that something is not working correctly in my "labeled for" loop. It's suppose to ask the user for his user name only 5 times, but it asks forever, like an infinite loop. Also, I want it to write to the user only once that I couldn't find his profile, so I've put it outside the for loop, but it shows up in every iteration.

any help will be appericiated.

else {
    System.out.println("Sorry couldn't find your user profile " + userName + ".");
    // If profile wasn't found, ask to create a new one.
    search:
    for(int i=0; i<5; i++) {    
        System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
        try{
            BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
            String addNewUser = answer.readLine();
            // If user pressed Y than write the new user name to myFile.txt
            if (addNewUser.toLowerCase().startsWith("y")) {
                if(addNewUser.length() == 1){
                    System.out.println("Please enter a new user name:");
                    BufferedReader readNewUser = new BufferedReader(new InputStreamReader(System.in));
                    Stri开发者_开发技巧ng newUserName = readNewUser.readLine();
                    PrintWriter write = new PrintWriter("d:\\profile.txt");
                    write.print(newUserName);
                    write.close();
                    break search;
                } else {
                    System.out.println("You've mistyped, please enter only one char:"); 
                    break;
                }
            } else {
                System.out.println("You've mistyped, the answer can only be Y or N. Try again:");   
            }


I think that you misunderstand what break does. Break will exit the loop and move on with your code. Breaking to a label allows you to break out of a specific loop, however you only have 1 loop, so that code is just redundant.
The command you're looking for is continue, which will skip to the next iteration of the loop.

I'd suggest reading this Oracle article about break and continue.


First: you have to replace the second break with continue.
Second: correct the end of the method. You have to check if the user has inserted a "n":

if (addNewUser.toLowerCase().startsWith("n")) {
   // do something...
}else {
   System.out.println("You've mistyped, the answer can only be Y or N. Try again:");   
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜