gpt4 book ai didi

java - 如何在 Java 中避免 else if 马拉松?

转载 作者:行者123 更新时间:2023-11-30 05:51:55 26 4
gpt4 key购买 nike

我正在开始 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”?随着更多的陈述,这变得非常乏味。请记住,我是初学者,这段代码几乎是我目前能力的极限。

最佳答案

你可以像这样使用数组:

String[] planets = { "Mercury", "Venus", "Earth", "Mars" };
int moons[] = { 0, 0, 1, 2 };

并调用:

if (rI >= 0 && rI < planets.length) {
question(planets[rI], moons[rI]);
}

关于java - 如何在 Java 中避免 else if 马拉松?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12231011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com