我正在尝试使这个程序打印出以列表单词中某个字母开头的单词。例如,如果输入字母“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);
}
}
}
默认情况下,扫描程序会破坏带有空格的单词。所以'远东'被扫描为'远'和'东'。使用分隔符来忽略空格。请参阅以下代码。
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 charycter");
char wrd = key.next().charAt(0);
keyboard.useDelimiter(System.getProperty("line.separator"));
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}