【发布时间】:2014-09-10 11:57:23
【问题描述】:
我正在为学校做一个项目,并被要求创建一个出售愚蠢物品的“商店”。在用户将适当数量的商品添加到他/她的购物车后,他们会选择结帐选项。这样做之后,会根据《星球大战》的知识向用户提示一个琐事问题。
对于课堂上的加分,我需要创建一个文件来存储几个问题和答案,然后检查它们是否正确。
我目前有 2 个文件,一个 trivaQ.txt 和一个 triviaA.txt。他们都持有“Question1”-“Question10”和“Answer1”-“Answer10”。 Question1的答案是Answer1,Question2的答案是Answer2,以此类推。
我编写了一个可以访问文件的简单 ReadFile 类,我正在尝试构建一个方法来选择正确答案(与问题索引相同),然后选择其他 2 个随机答案。
这是当前代码:
public int askA(){
int cAnswer = Question;
int answer1= (int)(Math.random() *10);
int answer2= (int)(Math.random() *10);
while(answer1 == cAnswer || answer1 == answer2){
answer1 = (int)(Math.random() *10);
}
while(answer2 == cAnswer || answer2 == answer1){
answer2 = (int)(Math.random() *10);
}
int x = random.nextInt(3)+1;
int y = random.nextInt(3)+1;
int z = random.nextInt(3)+1;
while( x == y || x == z){
x = random.nextInt(3)+1;
}
while( y == x || y == z){
y = random.nextInt(3)+1;
}
while( z == x || z == y){
z = random.nextInt(3)+1;
}
if(x > y && x > z){
//x is first
if(y > z){
//y is second
//z is third
System.out.println("[1.] " + itemData.get(cAnswer));
System.out.println("[2.] " + itemData.get(answer1));
System.out.println("[3.] " + itemData.get(answer2));
System.out.println("Answer is 1");
}else{
//z is second
//y is third
System.out.println("[1.] " + itemData.get(cAnswer));
System.out.println("[2.] " + itemData.get(answer2));
System.out.println("[3.] " + itemData.get(answer1));
System.out.println("Answer is 1");
}
}else if(y > x && y > z){
//y is first
if(x > z){
//x is second
//z is third
System.out.println("[1.] " + itemData.get(answer1));
System.out.println("[2.] " + itemData.get(cAnswer));
System.out.println("[3.] " + itemData.get(answer2));
System.out.println("Answer is 2");
}else{
//z is second
//x is third
System.out.println("[1.] " + itemData.get(answer1));
System.out.println("[2.] " + itemData.get(answer2));
System.out.println("[3.] " + itemData.get(cAnswer));
System.out.println("Answer is 2");
}
}else if(z > y && z > x){
//z is first
if(y > x){
//y is second
//x is third
System.out.println("[1.] " + itemData.get(answer2));
System.out.println("[2.] " + itemData.get(answer1));
System.out.println("[3.] " + itemData.get(cAnswer));
System.out.println("Answer is 3");
}else{
//x is second
//y is third
System.out.println("[1.] " + itemData.get(answer2));
System.out.println("[2.] " + itemData.get(cAnswer));
System.out.println("[3.] " + itemData.get(answer1));
System.out.println("Answer is 3");
}
}
System.out.println("X is - " + x);
System.out.println("CorrectAnswer --- " + cAnswer);
return x;
}
此方法目前无法按我的意愿工作。它选择一个问题,然后选择正确答案和 2 个随机答案;它没有按正确的顺序对它们进行排序。
我检查返回的值 x 是否等于用户输入,虽然它可能工作了 6/10 次,但失败了 4/10 次。
有没有更有效的方法来做到这一点?我的代码出了什么问题?
【问题讨论】:
-
在什么情况下会失败?
-
如果你想让你的代码更高效,你可能想看看codereview.stackexchange.com
-
@ Dave Newton - 当我运行程序时,它没有正确排序它们,所以 cAnswer 作为第二个选项打印出来,但 x 值为 3。