私はJavaプログラミングを始めており、各惑星の衛星数をテストするプログラムを作成しました。これは、惑星が4つしかない短縮版です。
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);
}
}
}
「elseif」を何度も書く必要がないようにするにはどうすればよいでしょうか。これは、ステートメントが増えると非常に面倒になります。私は初心者であり、このコードは私の現在の能力の限界についてのものであることを忘れないでください。