JAVAutil。扫描器如何在Java中计算字符串中指定字符的实例?
我在这里找到了所有相关的东西,但由于某种原因,没有任何帮助。每当我运行此操作时,结果总是为0。不,我不能使用其他库来实现这一点(我看到了一些非常棒的解决方案,它们只包含一行内容,但我做不到)
public void process()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your String:");
String in_string = input.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.println("Press 1 to count the occurrence of a particular letter.");
System.out.println("Press 2 to count the total words in your input sentance.");
System.out.println("Press 3 to change your input sentance.");
System.out.println("Press 4 to exit.");
int option = input2.nextInt();
if (option==1)
{
System.out.println("Choose your letter: ");
String in_occurence = input.nextLine();
for(int i = 0 ; i < in_string.length(); i++)
{
if(in_occurence.equals(in_string.charAt(i)))
{
charCount++;
}
}
System.out.println(charCount);
}
# 1 楼答案
您正在使用
String#equals()
将String
与char
进行比较。那将永远给你false
例如:
在比较之前,应通过获取索引0处的字符,将
String
转换为char
:或者,只需将
in_occurrence
声明为char
类型:# 2 楼答案
您正在将一个
String
与一个char
进行比较,即使字符串包含该字符,它也永远不相等你想要的是