java如何从用户输入的单词或短语中读取单个字符
这里的第一个问题。已经做了一些研究,但没有运气。我想我的代码中几乎所有内容都是正确的,但我无法让它工作。它需要从用户输入的字符串或短语中读取单个字符,然后打印出找到它的次数。我是java初学者,非常感谢您的帮助!!谢谢
import java.util.Scanner;
public class CountCharacters{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int timesFound;
String stringSearched, characterSearched;
System.out.printf("Enter a character for which to search: ");
characterSearched = input.next();
System.out.printf("Enter the string to search: \n");
stringSearched = input.nextLine();
int numberOfCharacters = stringSearched.length();
timesFound = 0;
for (int x = 0; x < numberOfCharacters; x++)
{
char charSearched = characterSearched.charAt(0);
if ( charSearched == stringSearched.charAt(x))
timesFound++;
System.out.printf("\nThere are %d occurrences of \'%s\' in \"%s\"",
timesFound, characterSearched, stringSearched);
}
}
}
# 1 楼答案
请在代码中注释掉这一行:
并替换为以下两行
nextLine()
将位置设置为下一行的开头。 所以你需要另一个input.next()
这是我在这个论坛上的第一个答案。 所以请原谅我可能犯的任何礼仪错误
# 2 楼答案
看看for循环。它在做你想做的事吗?我觉得里面的代码太多了。以下是我将如何完成你的任务
System.in
读取两次,并将输入分别分配给characterSearched
stringSearched
初始化计数器,就像使用
timesFound
从
characterSearched
中获取第一个字符在字符串
stringSearched
上循环并计数打印结果