Java 如何从用户输入的单词或短语中读取单个字符
这里的第一个问题。已经做了一些研究,但没有运气。我想我的代码中几乎所有内容都是正确的,但我无法让它工作。它需要从用户输入的字符串或短语中读取单个字符,然后打印出找到它的次数。我是java初学者,非常感谢您的帮助!!谢谢Java 如何从用户输入的单词或短语中读取单个字符,java,input,console,Java,Input,Console,这里的第一个问题。已经做了一些研究,但没有运气。我想我的代码中几乎所有内容都是正确的,但我无法让它工作。它需要从用户输入的字符串或短语中读取单个字符,然后打印出找到它的次数。我是java初学者,非常感谢您的帮助!!谢谢 import java.util.Scanner; public class CountCharacters{ public static void main(String[] args) { Scanner input = new Scanne
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);
}
}
}
import java.util.Scanner;
公共类计数字符{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
找到了int-times;
字符串字符串搜索,字符搜索;
System.out.printf(“输入要搜索的字符:”);
characterSearched=input.next();
System.out.printf(“输入要搜索的字符串:\n”);
stringSearched=input.nextLine();
int numberOfCharacters=stringSearched.length();
timesFound=0;
for(int x=0;x
看看for循环。它在做你想做的事吗?我觉得里面的代码太多了。以下是我将如何完成你的任务
- 从
中,将输入分别分配给系统中读取两次。在
characterSearched
stringSearched
- 初始化计数器,就像使用
timesFound
int timesFound = 0;
- 从
characterSearched
char charSearched = characterSearched.charAt(0);
- 在字符串
上循环并计数stringSearched
for (int x = 0; x < stringSearched.length(); x++){ if (charSearched == stringSearched.charAt(x)) timesFound++; }
// stringSearched = input.nextLine();
并替换为以下两行
input.nextLine();
stringSearched = input.next();
nextLine()
将位置设置为下一行的开头。
因此,您需要另一个输入。next()
这是我在这个论坛上的第一个答案。
所以请原谅我可能犯的任何礼仪错误。看起来不错。将打印输出移出循环
input.nextLine();
stringSearched = input.next();