简体   繁体   English

Java 变量问题

[英]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.我正在编写一个程序来比较两个字符串之间的差异,但我收到了变量 shortS 的错误,它是两个字符串中较短的字符串。 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删除 shortS 之前的所有其他 int 声明

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; int shortS = length2;

Just type只需输入

shorterS = length2;较短S = 长度2;

This goes for both cases.这适用于两种情况。 The reason is because you already have a variable type int declared with the same name.原因是因为您已经有一个使用相同名称声明的变量类型 int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM