-3

I am writing a program that compares the difference between two strings, and I am getting an error with the variable shorterS, which is the shorter string out of the two. The compiler is saying "the variable is already defined in main method"

int length1 = inputStr1.length();
int length2 = inputStr2.length();

int shorterS;
if(length1 <= length2)
   {int shorterS = length1;}
 else
   {int shorterS = length2;} 


int numDiff = 0;

for(int j=0; j<shorterS; j++)
{
  if(inputStr1.charAt(j) != inputStr2.charAt(j))
   System.out.print((j-1)+" "+inputStr1.charAt(j)+" "+inputStr2.charAt(j)); numDiff=numDiff++;

2 Answers2

0

You only need to declare a variable once and you do that on the 3rd line

int shorterS;

Delete all the other int declarations before shorterS

int length1 = inputStr1.length();
int length2 = inputStr2.length();

int shorterS;
if(length1 <= length2)
   {shorterS = length1;}
 else
   {shorterS = length2;} 


int numDiff = 0;

for(int j=0; j<shorterS; j++)
{
  if(inputStr1.charAt(j) != inputStr2.charAt(j))
   System.out.print((j-1)+" "+inputStr1.charAt(j)+" "+inputStr2.charAt(j)); numDiff=numDiff++;
Yan
  • 3,533
  • 4
  • 24
  • 45
0

Instead of typing again

int shorterS = length2;

Just type

shorterS = length2;

This goes for both cases. The reason is because you already have a variable type int declared with the same name.