第一个问题在这里。已经做了一些研究,但没有运气。我认为我的代码中大部分内容都正确无误,但我无法使其正常工作。它需要从用户输入的字符串或短语中读取单个字符,然后打印出其找到的次数。我是一个初学者在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);
}
}
}
什么不起作用? –
看起来不错。将打印输出移出循环 – iluxa