我正在爲一所學校的項目工作,並被要求創建一個銷售無聊物品的「商店」。在用戶將適當數量的物品添加到他/她的購物車後,他們選擇結賬選項。這樣做後,用戶會根據星球大戰的知識提示一個瑣事問題。如何最有效地選擇3個隨機問題並按隨機順序對其進行排序?
對於班級中的積分,我需要創建一個存儲多個問題和答案的文件,然後檢查它們是否正確。
我目前有2個文件,一個trivaQ.txt和一個triviaA.txt。他們都持有「問題1」 - 「問題10」和「答案1」 - 「答案10」。問題1的答案是答案1,問題2的答案是答案2,依此類推。
我寫的可以訪問該文件一個簡單的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倍。
有沒有更有效的方法來做到這一點?我的代碼出了什麼問題?
在什麼條件下(S)失敗? – 2014-09-10 12:00:09
如果你正在尋找讓你的代碼更有效,你可能想看看在http://codereview.stackexchange。com/ – 2014-09-10 12:02:04
@ Dave Newton - 當我運行該程序時,它沒有正確地對它們進行排序,因此第二個選項將打印出cAnswer,但x值爲3. – Connor 2014-09-10 12:02:34