gpt4 book ai didi

java - 如果用户输入无效 h

转载 作者:行者123 更新时间:2023-11-29 06:50:23 25 4
gpt4 key购买 nike

我是一名新程序员,我的类(class)有这项作业。我的问题是,如果用户输入无效并且执行了 else 语句,我该如何制作 System.out.println("Your Sign is "+ sign); 在 else 语句 not 执行之后出现,而不必在每个 if/else if 语句中都有 System.out.print

因此,如果用户输入无效,输出应该只是这样:“输入无效。请运行程序重试。”

import java.util.Scanner;

public class Sign {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int month, day;

System.out.println("What's your sign?");
System.out.print("Please enter the month of your birth (1-12): ");
month = input.nextInt();
System.out.print("Please enter the day of your birth (1-31): ");
day = input.nextInt();
String sign = "";

if ((month == 3 && (day >= 21 && day <= 31)) || (month == 4 && (day >= 1 && day <= 19))) {
sign = "Aries";
}
else if ((month == 4 && (day >= 20 && day <= 30)) || (month == 5 && (day >= 1 && day <= 20))) {
sign = "Taurus";
}
else if ((month == 5 && (day >= 21 && day <= 31)) || (month == 6 && (day >= 1 && day <= 21))) {
sign = "Gemini";
}
else if ((month == 6 && (day >= 22 && day <= 30)) ||(month == 7 && (day >= 1 && day <= 22))) {
sign = "Cancer";
}
else if ((month == 7 && (day >= 23 && day <= 31)) || (month == 8 && (day >= 1 && day <= 22))) {
sign = "Leo";
}
else if ((month == 8 && (day >= 23 && day <= 31)) || (month == 9 && (day >= 1 && day <= 22))) {
sign = "Virgo";
}
else if ((month == 9 && (day >= 23 && day <= 30)) || (month == 10 && (day >= 1 && day <= 22))) {
sign = "Libra";
}
else if ((month == 10 && (day >= 23 && day <= 31)) || (month == 11 && (day >= 1 && day <= 21))) {
sign = "Scorpio";
}
else if ((month == 11 && (day >= 22 && day <= 30)) || (month == 12 && (day >=1 && day <= 21))) {
sign = "Sagittarius";
}
else if ((month == 12 && (day >= 22 && day <= 31)) || (month == 1 && (day >= 1 && day <= 19))) {
sign="Capricon";
}
else if ((month == 1 && (day >= 20 && day <= 31)) || (month == 2 && (day >= 1 && day <= 18))) {
sign="Aquarius";
}
else if((month == 2 && (day >= 19 && day <= 29)) || (month == 3 && (day >= 1 && day <= 20))) {
sign="Pieces";
}
else {
System.out.println("Invalid Entry. Please run the program to try again.");
}

System.out.println("Your Sign is " + sign);
input.close();

}
}

最佳答案

您可以删除 else 子句,并使用 sign 的值作为有效输入的指示。

String sign = null;
if ((month == 3 && (day >= 21 && day <= 31)) || (month == 4 && (day >= 1 && day <= 19))) {
sign = "Aries";
} else if ...
...
} else if ((month == 2 && (day >= 19 && day <= 29)) || (month == 3 && (day >= 1 && day <= 20))) {
sign="Pieces";
}

if (sign != null) {
System.out.println("Your Sign is " + sign);
} else {
System.out.println("Invalid Entry. Please run the program to try again.");
}

关于java - 如果用户输入无效 h,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50384229/

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