0

I'm fairly new to java, and I've been trying to debug this code for some time now. I figured there must be something that I don't understand fully about Strings, so I thought I'd bite the bullet and ask on Stackoverflow.

int s1Len = s1.length();
int s2Len = s2.length();                
if(s1Len < s2Len){
    String bigInput = s2;
    String smallInput = s1;
}
else{
    String bigInput = s1;
    String smallInput = s2;
}

char[] bigCharArr = bigInput.toCharArray();
char[] smallCharArr = smallInput.toCharArray();

The error is that the compiler does not recognize the variables bigInput and smallInput when I'm trying to convert them into char arrays. Earlier I did not have the if/else statement to determine the larger string and it worked fine. I've used print statements, and Strings bigInput and smallInput are recognized until I'm past the if/else statements.

s1 and s2 are also other String class tokens from another String that I parsed earlier.

Any help would be appreciated. Thank you.

3 Answers 3

4

When you declare the variables within a block it is local to that block and wont be accessible from outside the block

declare your strings outside the block

      String bigInput = "";
      String smallInput = "";

      int s1Len = s1.length();
      int s2Len = s2.length();                
      if(s1Len < s2Len){
           bigInput = s2;
           smallInput = s1;
      }
      else{
           bigInput = s1;
           smallInput = s2;
      }

      char[] bigCharArr = bigInput.toCharArray();
      char[] smallCharArr = smallInput.toCharArray();
0
2

You're declaring the variable within the if/else block. This means that it is local to that if/else block and can only be seen between the brackets for that if/else block.

Try

int s1Len = s1.length();
int s2Len = s2.length();                
String bigInput = "";
String smallInput = "";

if(s1Len < s2Len){
    bigInput = s2;
    smallInput = s1;
}
else{
    bigInput = s1;
    smallInput = s2;
}

char[] bigCharArr = bigInput.toCharArray();
char[] smallCharArr = smallInput.toCharArray();
0
0

Define the

String bigInput;
String smallInput;

at the top of your code.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.