正如你在下面的代码注释中看到的,我想知道“”在下面的程序中的重要性。
“计数仍然停留在0,所以看起来”“似乎很重要。我以为“”的功能是在字符串之间放置空格。它在这里做什么?非常感谢!
package js01;
import java.util.Scanner;
//search 1
//user input of an alphabet and a sentence, return a count of that alphabet
public class J0306_search {
public static void main(String[] args) {
String str1;
String ch;
//must be a string type although the input will be a chracter because the user input is taken as a string
int count=0;
int i;
Scanner s=new Scanner (System.in);
System.out.println("enter a sentence");
str1=s.nextLine();
System.out.println("enter an alphabet that u would like to count");
ch=s.next();
for (i=0;i<str1.length();i++) {
if (ch.equals(""+str1.charAt(i))) {
//why is "" needed?
//
count++;
}
}
System.out.println("count is:"+count);
s.close();
}
}
发布于 2019-07-27 11:23:50
为什么需要"“?
str1.charAt(i)
返回一个char
。ch
是一个String
。如果在String
上使用equals
并传入char
,它将自动装箱为Character
,并且当类型不同时(在正确编写的equals
中),equals
总是返回false。
""+str1.charAt(i)
创建了一个字符串,这样您就可以将一个String
传递给equals
,所以它会比较这两个字符串,看看它们是否包含相同的字符。(另一种方式是String.valueOf(str1.charAt(i))
,它看起来更长,但生成的字节码更有效-尽管如果它处于热点中,JIT可能会对其进行优化。)
发布于 2019-07-27 11:22:26
它将str1.charAt(i)
转换为字符串,因此它是Character.toString(str1.charAt(i))
的替代方案
https://stackoverflow.com/questions/57231592
复制相似问题