Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: Is it possible to use a variable outside a loop that has been initialised inside a loop?

I'm a new programmer trying to practice by making a game. I want the player to be able to set their own name, as well as answer yes or no as to whether that name is correct. I did this by using a while loop. However, since the name is initialized inside the loop, I cannot use it outside. I was wondering if there was anyway to do so.

My code is probably very basic and messy. I apologize for that.

    Scanner input = new Scanner(System.in);
    String name;
    int nameRight = 0;

    while (nameRight == 0) {

        System.out.println("What is your name?");
        name = input.nextLine();

        System.out.println("So, your name is " + name + "?");
        String yayNay = input.nextLine();

        if (yayNay.equals("yes") || yayNay.equals("Yes")) {
            System.out.println("Okay, " + name + "...");
            nameRight++;

        } 
        else if (yayNay.equals("no") || yayNay.equals("No")) {

            System.out.println("Okay, then...");

        } 

        else {
            System.out.println("Invalid Response.");
        }

    }

So basically, I want String name to be initialized inside the loop, so I can use it outside the loop.

like image 257
max Avatar asked Dec 15 '22 08:12

max


1 Answers

The scope of a variable, limits the use of that variable to the scope it is defined in. If you want it used in a broader scope, declare it outside the loop.

However, since the name is initialized inside the loop, I cannot use it outside.

You have defined the variable outside the loop, so the only thing you need to do is to initialize it, as the error message you should get suggests.

String name = "not set";

while(loop) { 
     name = ...

     if (condition)
        // do something to break the loop.
}
// can use name here.

The basic problem is that the compiler cannot work out that the variable will be set in all possible code paths. There is two ways you can fix this without using a dummy value. You can use a do/while loop.

String name;
boolean flag = true;
do {
    name = ...
    // some code
    if (test(name))
        flag = false;
    // some code
} while(flag);

or drop the condition, as you don't need a counter.

String name;
for (;;) {
    name = ...
    // some code
    if (test(name)) {
       break;
    // some code if test is false.
}
like image 77
Peter Lawrey Avatar answered May 18 '23 14:05

Peter Lawrey