嗨,我是初学者,我想做一个测验数学游戏,我怎么能选择一个指定索引的随机数组,并使用它作为大小写值。
Random random=new Random();
int num1= random.nextInt(30);
int num2= random.nextInt(30);
System.out.println(num1+"+"+num2+"=");
int result=num1+num2;
System.out.println("What is the answer of this operation?");
int sugg1=random.nextInt(100);
int sugg2=random.nextInt(100);
int[] array = {sugg1,sugg2,result};
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
int randomIndexToSwap = rand.nextInt(array.length);
int temp = array[randomIndexToSwap];
array[randomIndexToSwap] = array[i];
array[i] = temp;
}
System.out.println(Arrays.toString(array));
switch (Arrays.toString(array)) {
//I NEED HELP HERE HOW CAN I SELECT A SPECIFY INDEX OF THE RANDOM ARRAY AND USE IT AS CASE VALUE
case array:
}
您可以使用switch(array[yourIndex]){case element: ...}
我不太明白你想做什么。
值版本:
// Print for example [14,21,30] if question is 10+11
System.out.println(Arrays.toString(array));
// You want the user to select the answer
System.out.print("Please type the good answer : ");
Scanner scan = new Scanner(System.in);
switch(scan.nextInt()){
case result:
System.out.println("Good answer!");
break;
default:
System.out.printtln("Bad answer!");
}
索引版本:
// Print for example [14,21,30] if question is 10+11
System.out.println(Arrays.toString(array));
// You want the user to select the answer index
System.out.print("Please type the good answer : ");
Scanner scan = new Scanner(System.in);
int index = scan.nextInt();
if(index >= 0 && index <= array.length) {
switch(array[index]){
case result:
System.out.println("Good answer!");
break;
default:
System.out.printtln("Bad answer!");
}
} else {
System.out.println("Selected index does not exist in the array");
}
顺便说一下,如果sugg1
!=sugg2
!=answer
可能是好的,因为在下面的代码中,值不是不可能相同:
int sugg1=random.nextInt(100);
int sugg2=random.nextInt(100);
int[] array = {sugg1,sugg2,result};