从txt文件中检索一个随机字并且没有输出,并且没有编译器错误java [英] retrieving a random word from a txt file and getting no output, and no compiler error java

查看:137
本文介绍了从txt文件中检索一个随机字并且没有输出,并且没有编译器错误java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法更改程序的shell,最终目标是从txt文件中的单词列表中选择一个随机单词。我已经扫描了很多次,逐个浏览代码,尝试了许多不同的东西,但每次运行它,它编译没有问题,但我从来没有得到任何输出。我甚至尝试在私人功能中插入一些输出,但无济于事。任何人都可以看到我的代码有什么问题或者可以向我解释发生了什么?

i cannot change the shell of the program, the end goal is to choose a random word from a list of words in a txt file. i've scanned through this many many times, gone through the code one by one, tried many different things, but every time i run it, it compiles without a problem but i never get any output. i've even tried inserting some output in the private functions, but to no avail. can anyone see what is wrong with my code or can explain to me what is happening?

import java.util.*;

    class PartOfSpeech
    {
      private String[] words;
      private Random random;
      private String filename;

      public PartOfSpeech(String filename)
      {
        this.filename = filename;
        this.read();
      }
      //this picks a random number and uses that number for the index of the array for which to return
      public String getRandomWord()
      {
        int index;
        index = random.nextInt(this.getCount());
        return words[index];
      }
      //this gets a count of how many lines of txt are in the file
      private int getCount()
      {
        Scanner fr = new Scanner(this.filename);
        int count = 0;
        while(fr.hasNextLine())
        {
         count++;
        }
       return count; 
      }
      //this creates a scanner and inserts each word from the txt file into an array
      private void read()
      {
        Scanner fr = new Scanner(this.filename);
        for(int i=0; i<this.getCount(); i++)
        {
         words[i] = fr.nextLine(); 
        }
      }

      public static void main(String[] args)
      {
        PartOfSpeech n = new PartOfSpeech("nouns.txt");
        System.out.print(n.getRandomWord());
      }
    }


推荐答案

构造函数扫描程序(字符串源)实际上解析源字符串的内容,而不是将其视为文件名,您需要

Constructor Scanner(String source) actually parse the content of the source string, instead of treating it as a file name, You need

new Scanner(new File(fileName))

这篇关于从txt文件中检索一个随机字并且没有输出,并且没有编译器错误java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆