【问题标题】:Java search programJava 搜索程序
【发布时间】: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);
        }
    }
}

【问题讨论】:

    标签: java search


    【解决方案1】:

    默认情况下,扫描器会使用空格分隔单词。所以“远东”被扫描为“远”和“东”。改用分隔符来忽略空格。参考下面的代码。

    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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多