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++;
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++;
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.