【发布时间】:2017-12-16 06:09:19
【问题描述】:
我正在尝试制作这个程序,它可以打印出以列表单词中的某个字母开头的单词。例如,如果您输入字母“e”,它应该只打印以字母“e”开头的单词,但由于某种原因,它正在读取诸如“远东”之类的单词,即使它不以字母“e”开头。有什么建议吗?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class words {
public static void main(String[] args) throws IOException {
Scanner key = new Scanner(System.in);
File wordfile = new File("wrds.txt");
if(wordfile.exists()){
Scanner keyboard = new Scanner(wordfile);
int counter = 0;
System.out.println("Enter a character");
char wrd = key.next().charAt(0);
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}
【问题讨论】: