从数组或ArrayList对象中随机选择。该程序应重复执行,直到用户准备退出为止

时间:2019-02-09 03:53:46

标签: java

我尝试从文件中获取随机行。

 import java.util.Scanner;
 import java.util.Random;
 import java.io.*;

 public class Magic8Ball {
    public static void main(String[] args)throws IOException{
       FileReader file= new FileReader("8_ball_responses.txt");
       BufferedReader input= new BufferedReader(file);
       Scanner keyboard= new Scanner(System.in);
       Random gen= new Random();
       char letter;
       String ques;
       String choice;
       System.out.println("What is your question?");
       do {
          ques= keyboard.nextLine();
          String[] answers= new String[12];
          Object lines;
          for(int i=0; i<lines.length;i++){
             answers[i]= input.readLine();
          }
          int finalAns= gen.nextInt(answers.length);
          System.out.println(answers[finalAns]);      
          System.out.println("Do you have another question? (yes or no):");
          choice= keyboard.nextLine();
          letter=choice.charAt(0);
       } while(letter!='n' && letter!='N');
    }
 }

8_ball_responses.txt:

Yes, of course!
Without a doubt, yes.
You can count on it.
For sure!
Ask me later.
I'm not sure.
I can't tell you right now.
I'll tell you after my nap.
No way!
I don't think so.
Without a doubt, no.
The answer is clearly NO.

我不知道如何显示随机响应

1 个答案:

答案 0 :(得分:0)

当前,每次用户提出问题时,您都在阅读整个文件,您不应该这样做。相反,请阅读一次并保留它。

然后,您使用java.util.Random生成一个随机结果。使用nextInt(to)函数获得结果。

public class Magic8Ball {
    public static void main(String[] args)throws IOException{
       FileReader file= new FileReader("8_ball_responses.txt");
       BufferedReader input= new BufferedReader(file);
       Scanner keyboard= new Scanner(System.in);
       Random gen= new Random();
       char letter;
       String ques;
       String choice;
       String[] answers= new String[12]; // Reading the file only once, outside the question loop
       Object lines;
       for(int i=0; i<lines.length;i++){
          answers[i]= input.readLine();
       }
       Random random = new Random(); // get a random number generator here.
       System.out.println("What is your question?");
       do {
          ques= keyboard.nextLine();
          int finalAns= gen.nextInt(answers.length);
          System.out.println(answers[random.nextInt(12)]); // use the random number generator here where you need it.
          System.out.println("Do you have another question? (yes or no):");
          choice= keyboard.nextLine();
          letter=choice.charAt(0);
       } while(letter!='n' && letter!='N');
    }
 }