Do while loop not working? (Cannot find variable)

前端 未结 3 374
借酒劲吻你
借酒劲吻你 2021-01-29 08:43

I am having trouble with my do while loop not finding my variable to test if the condition is true or not. Here is my code:

import java.util.Scanner;
public clas         


        
相关标签:
3条回答
  • 2021-01-29 08:47

    play must be declared before the do-while loop in order to be in scope of the while condition.

    String play = "";
    do {
        ...
        play = prompt.next();
    } while(play.equalsIgnoreCase("yes"));
    
    0 讨论(0)
  • 2021-01-29 08:52

    You are out of scope because you are using a do{} while() loop. When java reaches the do statement, it skips down to your while statement to make sure it returns true. It doesn't even see the code in the middle until after that.

    It's much easier to see the correct scope of a variable if you use a while(condition){body} statement since the variable is at the top, where we naturally expect the code that is executed first to be.

    So I would use a while loop as explained above, and you will have to declare the play variable before that line. Hope that works :)

    0 讨论(0)
  • 2021-01-29 09:09

    Instead of declaring the play as a local variable declare it as a class level variable.

    String play;
    do {
        ...
        play = prompt.next();
    } while(play.equalsIgnoreCase("yes"));
    
    0 讨论(0)
提交回复
热议问题