Jonny Gjeltema Jonny Gjeltema - 2 months ago 17
Java Question

Java Variable Issue

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++;

Yan Yan
Answer

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++;