user3002473
user3002473

Reputation: 5074

Java Error; could not resolve variable name

Forgive me for asking a very basic question, I've only just begun learning Java and something doesn't make much sense to me. I was working on some simple practice problems and then I come across this one:

Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

Here is the link for anyone interested. This didn't look hard, so I wrote this;

public String front3(String str){
  if (str.length() < 3){
    String front = str;
  } else {
    String front = str.substring(0, 3);
  }
  return front + front + front;
}

This doesn't run. Instead it gives an exception saying the name front could not be resolved. What? Why would this happen, either way String front is getting initialized in either the if block or the else block, to a strictly Pythonic coder this is doesn't make sense. The example code showed how I have to have the line String front; as the second line, to initialize an empty string.

What under the hood is going on that would cause this not to work in Java? Try to explain it in a way that a Pythonista would understand! :)

Also I assume I'm going to get downvoted into oblivion as I'm sure this is a common problem that many beginners run into, and there is probably already an answer somewhere on SO.

Upvotes: 1

Views: 100

Answers (2)

rgettman
rgettman

Reputation: 178293

The scope of a declared variable is limited to the block in which it's located, so front immediately goes out of scope as soon as it's initialized.

Any local variable declared inside any {}, even the {} for an if statement, is not visible outside those {}.

Declare it before the if so it remains in scope for the duration of the method.

String front;
if (str.length() < 3){
  front = str;
} else {
  front = str.substring(0, 3);
}

Upvotes: 4

Rob
Rob

Reputation: 12872

Initialize your variable outside the if.

public String front3(String str){
  String front;
  if (str.length() < 3){
    front = str;
  } else {
    front = str.substring(0, 3);
  }
  return front + front + front;
}

Upvotes: 1

Related Questions