0

Here is my code. It's supposed to take in two strings and compare their differences character by character.

import java.util.Scanner;
public class Positions {
 public static void main(String[] args){
  Scanner scan = new Scanner(System.in);
  String first = scan.next();
  String second = scan.next();
  if(first.length()>second.length()){
     int length = first.length();
  }else{
     int length = second.length();
  }
  for(int i=0; i<length; i++){
     if(first.charAt(i)!=second.charAt(i)){
        System.out.print(i+" "+first.charAt(i)+" "+second.charAt(i));
     }
  }
 }
}

I am getting this error when I try to compile:

 ----jGRASP exec: javac -g Positions.java
Positions.java:12: error: cannot find symbol
      for(int i=0; i < length; i++){
                       ^
  symbol:   variable length
  location: class Positions
1 error

 ----jGRASP wedge: exit code for process is 1.
 ----jGRASP: operation complete.
user2864740
  • 60,010
  • 15
  • 145
  • 220
Snubber
  • 986
  • 1
  • 10
  • 24

1 Answers1

7

Your length variable is declared and initialized in each case of if and else and then immediately discarded as out of scope when the block ends.

Declare it before the if and initialize it in each case, so it remains in scope for the for loop further down.

int length;
if(first.length()>second.length()){
   length = first.length();
}else{
   length = second.length();
}
rgettman
  • 176,041
  • 30
  • 275
  • 357