如何随机化在Java中读取的文本文件 [英] How to randomize text file read in java
问题描述
我正在尝试做一个q&一个程序,将读取一个问题,有4个选择.然后阅读答案并将其与正确答案进行比较.然后增加玩家分数,
我的问题是,我在运行程序时总是得到null.您能否帮助我确定我的程序出了什么问题.我也使java.lang.nullexception和index数组超出范围.
文件结构如下所示:
q
a
b
c
d
ans
其中q是问题,a,b,c,d是选择.而答案是正确的答案,可以与玩家的答案进行比较.
I''m trying to do a q & a program which will read a question, 4 choices. Then read the answer and compare it to the correct answer. Then increments the player score,
My problem is, I always get null when I run the program. Could you please help me determine what''s wrong with my program. I also get java.lang.nullexception and index array out of bounds.
File structure looks like this:
q
a
b
c
d
ans
where q is the question a,b,c,d are the choices. And the ans is the correct answer which will be compared to the players answer.
public static String[] q=new String[50];
public static String[] a=new String[50];
public static String[] b=new String[50];
public static String[] c=new String[50];
public static String[] d=new String[50];
public static char[] ans=new char[50];
try {
FileReader fr;
fr = new FileReader (new File("F:\\qa.txt"));
BufferedReader br = new BufferedReader (fr);
while (br.readLine()!= null) {
for(int ox=0;ox<5;ox++){
q[ox]= new String();
a[ox]= new String();
b[ox]= new String();
c[ox]= new String();
d[ox]= new String();
q[ox] = br.readLine();
a[ox]=br.readLine();
b[ox]=br.readLine();
c[ox]=br.readLine();
d[ox]=br.readLine();
String strtemp=br.readLine();
ans[ox]=strtemp.charAt(0);
}
}
br.close();
} catch (Exception e) { e.printStackTrace();}
for(int yy=0;yy<90;yy++){
int ran= random(1,70);
System.out.println(q[ran] + "\n" + a[ran] + "\n" + b[ran] + "\n" + c[ran] + "\n" + d[ran] + "\n" + "\n" + "Answer: ");
String strans=x.nextLine();
char y=strans.charAt(0);
if(y==ans[ran]){
System.out.println("check!");
score++;
System.out.println("Score:" + score);
}else{
System.out.println("Wrong!");
}
}
这是我用于随机化的方法:
Here''s the method that I use for randomizing:
[CODE] public int random(int min, int max){
int xx;
xx= (int) ( Math.random() * (max-min + 1))+ min;
return xx;
}
推荐答案
for(int ox = 0; ox< 5; ox ++){ 4?
for(int yy = 0; yy< 90; yy ++){和yy< 89?
您从0开始,这是常见的误入界误区.
null也可能是由此引起的..
for(int ox=0;ox<5;ox++){ are you sure its not ox < 4?
for(int yy=0;yy<90;yy++){ and yy < 89?
your starting at 0, its a common mistake for out of bounds exceptions.
the null might be caused by this too..
这篇关于如何随机化在Java中读取的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!