5

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.

5
  • no it´s not possible to use it outside of the look, if the definition of the variable is inside the loop. But since name is defined outside the loop you should be able to use it outside the loop aswell. Commented Mar 9, 2016 at 7:44
  • No. you might be able to use it's value, if you copy it to a variable that is declared outside of the loop, but then you could just as easily declare the variable itself out of the loop. Commented Mar 9, 2016 at 7:45
  • Okay thanks. I'll just have to change my code then. Commented Mar 9, 2016 at 7:47
  • 1
    @max declare name variable outside the loop and initialize it it to null and when it goes to the inner loop it gets reinitialized so then wherever you access the value of the variable outside the loop the new value will be displayed Commented Mar 9, 2016 at 7:49
  • Please don't confuse javascript and java as they are very different languages, I assume this is not related to javascript. Commented Mar 9, 2016 at 7:51

3 Answers 3

10

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.
}
Sign up to request clarification or add additional context in comments.

3 Comments

Not so sure he can use name there because your loop never ends. I realize it is just an example, but for the sake of new programmers everywhere, add a comment inside loop indicating that some work gets done there or perhaps that name gets set?
how about passing the variable values to outside functions which is changed inside the loop ?
@sathya Java doesn't support this e.g. C#'s yield Instead you can use Streams with a lambda generating multiple results (or returning a Collection of results)
2

NO, it wouldn't be possible as the scope of the variable declared in the loop is limited to the loop. So the variable is not longer accessible.

while(i < 10){
    int x = 2;
    i++;
}

Now, the scope of x would be from the point at which it is defined to the end of the enclosing block. So the variable here would be created and destroyed 10 times if i starts from 0.

1 Comment

Please avoid link references.
0

First there's the "scope", this is the issue you're touching at the moment. The way you have done this so far seems to be a good way of doing it and you WILL be able to use/access the name variable from anywhere in the code after line 2 from what you have linked.

The scope basically says, you can use the variable inside the curly brackets {} that you DECLARED it inside. I assume that you have your code inside some main method at the moment, thus you can access the name variable from anywhere after the line

String name;

as long as you don't try to use it after the closing }, corresponding to a opening { that occurred before name is declared.

SOLUTION: What you have to do to use a variable outside a loop, is to declare it before the loop begins, you don't have to initialize the variable before, but you have to initialize it before you try to use it for anything. In general, if you need to access the variable in a wider area, you must declare that variable before you enter the not-so-wide area.

Notice that by declaring I mean creating the variable reference by using "String" in front of "name". Don't confuse it with initializing it or assigning a value to it, that has nothing to do with the scope, only declaration sets the scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.