正如您在下面的代码注释中看到的,我想知道“”在下面的程序中的重要性。我试图在没有
的情况下运行程序
""并且计数仍然停留在 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();
}
}
最佳答案
why is "" needed?
str1.charAt(i)
返回一个 char
。 ch
是一个 String
。如果您在 String
上使用 equals
并传入 char
,它会自动装箱为 Character
和 equals
在类型不同时总是返回 false(在正确编写的 equals
中)。
""+str1.charAt(i)
创建一个字符串,以便您将 String
传递给 equals
,因此它比较两个字符串,看它们是否有相同的字符。 (另一种方法是 String.valueOf(str1.charAt(i))
,它看起来更长但生成的字节码更高效——尽管 JIT 可能会在热点中对其进行优化。)
关于Java程序关于("")的重要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57231592/