我正在开始 Java 编程,并且我编写了一个程序来测试每个行星有多少颗卫星。这是一个只有四个行星的缩短版本。
import java.util.Scanner;
import java.util.Random;
public class one {
public static void main(String args[]){
//SET VARIABLES
String zero="Mercury", one="Venus", two="Earth", three="Mars";
//SET VARIABLES
for (int x=1; x<=1000; x++){
System.out.println("Moons");
Random r = new Random();
for (int y=1; y<=1; y++){
int rI = r.nextInt(4);
if (rI == 0){
question(zero,0);
}
else if (rI == 1){
question(one, 0);
}
else if (rI == 2){
question(two, 1);
}
else if (rI == 3){
question(three, 2);
}
}
}
}
public static void question(String n, int num){
Scanner input = new Scanner(System.in);
System.out.print("How many moons does " + n + " have? ");
int ans = input.nextInt();
if (ans == num){
System.out.println("Correct!");
}
else if (ans != num){
System.out.println("Incorrect!");
question(n, num);
}
}
}
我将如何不必多次写“else if”?随着更多的陈述,这变得非常乏味。请记住,我是一个初学者,这段代码是关于我目前能力的限制。