简体   繁体   English

想要从文本文件中随机选择单词,而不是从文本文件中打印所有内容

[英]Want to randomly choose word from text file and instead printing everything from text file

I want the compiler to randomly choose a word from text instead of printing everything from a text file.我希望编译器从文本中randomly选择一个单词,而不是从文本文件中打印所有内容。 Right now the code below is printing everything from the text file.现在下面的代码正在打印文本文件中的所有内容。 I think there is something wrong with my getWord method because when I call the getWord method from the main function I get an error .我认为我的getWord方法有问题,因为当我从主函数调用getWord方法时error

public class TextFile {

        protected static Scanner file;
        protected static List<String> words;


        public TextFile(){
            words = openFile();
        }

        private List<String> openFile() {

            //List<String> wordList = new ArrayList<String>();

                try {
                    file = new Scanner(new File("words.txt"));

                } catch (FileNotFoundException e) {
                    System.out.println("File Not Found");
                } catch (Exception e) {
                    System.out.println("IOEXCEPTION");
                }

                return words;
        }

        public void readFile() throws FileNotFoundException {

            //ArrayList<String> wordList = new ArrayList<String>();

            while(file.hasNext()){
                String a = file.nextLine();
                //Collections.shuffle(words);
                //String pickWord = words.get(1);
                //String[] a = 
                System.out.println(a);
            }
        }

        public void closeFile() {
            file.close();
        }

        public String getWord() {

            Random r = new Random(words.size());
            String randomWord = words.get(r.nextInt());
            //System.out.println(randomWord);

            return randomWord;
        }

        public static void main(String[] args) throws FileNotFoundException {

            try {

                TextFile file = new TextFile();

                file.openFile();
                file.readFile();

                file.closeFile();

            } catch (Exception e) {
                System.out.println("IOEXCEPTION");
            }
        }
    }

in the openfile method you are retuning a "word" variable which is null assign value to the variable在 openfile 方法中,您正在重新调整一个“word”变量,该变量为空,为变量赋值

the error is coming from the {getword();} because you are accessing properties of a null variable its a error错误来自 {getword();} 因为您正在访问空变量的属性,这是一个错误

     public List<String> readFile() throws FileNotFoundException {
       while(file.hasNext()){
            String a = file.nextLine();
            words.add(a);
            System.out.println(a);
        }
       return words;
    }

inside the open file method at the return statement line call "return readfile();"在返回语句行的打开文件方法中调用“return readfile();” and try ur code\\并尝试您的代码\\

no need to call readfile method inside the main method无需在 main 方法中调用 readfile 方法

You are getting exception while calling getWord method as it throws IndexOutOfBoundsException at line String randomWord = words.get(r.nextInt());您在调用 getWord 方法时遇到异常,因为它在String randomWord = words.get(r.nextInt());行处抛出IndexOutOfBoundsException . .

PFB correction to getWord method:getWord方法的 PFB 修正:

public String getWord() {
    //You can use any approach..Random or Collections
    //Random r = new Random();      
    //String randomWord = words.get(r.nextInt(words.size()));

    Collections.shuffle(words);
    String randomWord = words.get(1);

    return randomWord;
}

Again you should populate words field correctly:同样,您应该正确填充words字段:

public void readFile() throws FileNotFoundException {

    words = new ArrayList<String>();

    while (file.hasNext())
        words.add(file.nextLine());
}

Try this.尝试这个。 You don't need to use the getWord() method in the main.您不需要在 main 中使用 getWord() 方法。 Also, create a constructor for the class:此外,为该类创建一个构造函数:

public TextFile() {
}

Your openFile() method doesn't need to return string.您的 openFile() 方法不需要返回字符串。

    private void openFile() {


          try {
                file = new Scanner(new File("words.txt"));

            } catch (FileNotFoundException e) {
                System.out.println("File Not Found");
            } catch (Exception e) {
                System.out.println("IOEXCEPTION");
            }
}

Here is your readFile() method: 1)Read file 2)Split a line of words into each word and put it in array 3)Then, random word这是您的 readFile() 方法:1)读取文件 2)将一行单词拆分为每个单词并将其放入数组 3)然后,随机单词

public void readFile() throws FileNotFoundException {

    //  List<String> wordList = new ArrayList<String>();


        while(file.hasNext()){


            String line = file.nextLine(); //read file one line at a time

            String[] parseWords = line.split(" "); //Parse what you read


            int index = new Random().nextInt(parseWords.length);

            String randW = parseWords[index];
            System.out.println(randW);

        }
    }

In your main method:在您的主要方法中:

TextFile file1 = new TextFile ();

file1.openFile();
file1.readFile();
file1.closeFile();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM