我正在尝试编写文字游戏。有些问题是随机显示的,用户会尝试正确回答。
我用开关大小写匹配了问题和答案,但由于无法弄清楚如何在String数组中找到单词,所以无法检查它是否正确。同样,由于该方法,开关盒中也存在错误。
import java.util.Scanner;
import java.util.Random;
public class Odev {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter the 1 for answer or 2 for requesting a letter.");
int first= input.nextInt();
String[] question = new String[9];
String [] answer=new String[9];
question=array(question);
answer=array2(answer);
Random b= new Random();
int randomNumber=b.nextInt(question.length);
if(first==1) {
System.out.println(question[randomNumber]);
System.out.println(randomNumber);
String a1=input.next();
switch (randomNumber) {
case 0: equalM(a1, answer[0]);
break;
case 1: equalM(a1, answer[1]);
break;
case 2:equalM(a1, answer[2]);
break;
case 3:equalM(a1, answer[3]);
break;
case 4:equalM(a1, answer[4]);
break;
case 5:equalM(a1, answer[5]);
break;
case 6:equalM(a1, answer[6]);
break;
case 7:equalM(a1, answer[7]);
break;
case 8:equalM(a1, answer[8]);
break;
}
}
}
public static String [] array(String [] question) {
question[0]="A beverage which is white and generally consumed in mornings";
question[1]="The natural satellite of earth";
question[2]="An adjective which describes people who have not adequate money";
question[3]="A furniture sit around for eating or studying";
question[4]="A group that consists a lot of soldier";
question[5]="A fruit which can be red, yellow and green";
question[6]="A tool for writing which consists graphite";
question[7]="A beverage which is consumed by people who need caffeine ";
question[8]="A term which is stand for the smallest group of the society ";
return question;
}
public static String [] array2(String [] answer) {
answer[0]="milk";
answer[1]="moon";
answer[2]="poor";
answer[3]="table";
answer[4]="army";
answer[5]="apple";
answer[6]="pencil";
answer[7]="coffee";
answer[8]="family";
return answer;
}
public static String[] equalM(String a1, String[] answer) {
for (int i=0; i<answer.length; i++) {
if(a1.equals(answer[i])) {
System.out.println("Correct you gained 500 points");
} else
System.out.println("Wrong.You lost 500 points");
}
return answer;
}
}
答案 0 :(得分:0)
您可以使用哈希图轻松完成此操作,但是如果您要坚持使用数组,则可以打印出所有答案选项及其索引号,然后读取用户键入的数字以获取正确答案。然后,您只需检查该数字是否等于用于生成问题的随机数即可。