I am trying to read a text file in java, basically a set of questions. With 4 choices and 1 answer. The structure looks like this:
question
option a
option b
option c
option d
answer
I have no trouble reading it that way:
public class rar{
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];
public static Scanner sr= new Scanner(System.in);
public static void main(String args[]){
int score=0;
try {
FileReader fr;
fr = new FileReader (new File("F:\\questions.txt"));
BufferedReader br = new BufferedReader (fr);
int ar=0;
for(ar=0;ar<2;ar++){
q[ar]=br.readLine();
a[ar]=br.readLine();
b[ar]=br.readLine();
c[ar]=br.readLine();
d[ar]=br.readLine();
String tempo=br.readLine();
ans[ar]=tempo.charAt(0);
System.out.println(q[ar]);
System.out.println(a[ar]);
System.out.println(b[ar]);
System.out.println(c[ar]);
System.out.println(d[ar]);
System.out.println("Answer: ");
String strans=sr.nextLine();
char y=strans.charAt(0);
if(y==ans[ar]){
System.out.println("check!");
score++;
System.out.println("Score:" + score);
}else{
System.out.println("Wrong!");
}
}
br.close();
} catch (Exception e) { e.printStackTrace();}
}
}
The code above is predictable. The for loop just increments. And it displays the questions based on order. What I want to do is to be able to randomize through the text file, but still maintaining the same structure. (q, a, b, c, d, ans). But when I try to do this:
int ran= random(1,25);
System.out.println(q[ran]);
System.out.println(a[ran]);
System.out.println(b[ran]);
System.out.println(c[ran]);
System.out.println(d[ran]);
System.out.println("Answer: ");
String strans=sr.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!");
}
And this is the method that I use for randomizing:
public static int random(int min, int max){
int xx;
xx= (int) ( Math.random() * (max-min + 1))+ min;
return xx;
}
There's the possibility that I get a null. What can you recommend that I would do so that I get no null when trying to randomize the questions? Can you see anything else that is wrong with my program?