【发布时间】:2013-11-04 02:29:45
【问题描述】:
我根据之前的建议更新了我的代码,它只读取我句子中的第一个单词,关于如何让它阅读整个句子的任何建议? (我必须使用 for 循环)
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count ++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
输出: 输入要搜索的字符 H 输入要搜索的字符串 你好吗 hello 中出现了 1 次 h
【问题讨论】:
-
至少试试你的作业或谷歌吧!
-
尝试使用
in.nextLine()而不是in.next() -
我试过了,就是那个代码
-
你在一小时前就已经问过这个问题了..stackoverflow.com/questions/19580911/…
-
谢谢@MadProgrammer