public class child {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int AGE;
System.out.println("Enter Child's number(s) of Days: ");
AGE = scan.nextInt();
if (AGE == 0 || AGE == 1){
System.out.println("Classification: New Born");
}
else if (AGE >= 2 && AGE <= 10){
System.out.println("Classification: Infant");
}
else if (AGE > 9 && AGE < 19){
System.out.println("Classification: New Born");
}
else if (AGE > 17 && AGE < 37){
System.out.println("Classification: TODDLER");
}
else if (AGE > 36 && AGE < 120 ) {
System.out.println("Classification: KID");
}
else{
System.out.println("Classification: Out of Range");
System.out.println("Enter a number again:");
AGE = scan.nextInt();
if (AGE == 0 || AGE == 1){
System.out.println("Classification: New Born");
}
else if (AGE >= 2 && AGE <= 10){
System.out.println("Classification: Infant");
}
else if (AGE > 9 && AGE < 19){
System.out.println("Classification: New Born");
}
else if (AGE > 17 && AGE < 37){
System.out.println("Classification: TODDLER");
}
else if (AGE > 36 && AGE < 120 ) {
System.out.println("Classification: KID");
}
else{
System.out.println("Classification: Out of Range");
System.out.println("Enter a number again:");
AGE = scan.nextInt();
}
}
}
}
所以我根据他们的天数对孩子进行了分类。
如何简化此代码,因为如果用户输入的数字超出范围,程序将提示用户输入一个值,但如果用户再次输入一个超出范围的数字,将停止提示用户输入另一个号码,因为如果我在其他地方放置另一个条件构造,它将使我的代码更长,所以我的问题是如何使我的代码更短但是程序将继续提示用户,如果输入的数字是超出范围。
示例输出 输入儿童的天数: 121 分类:超出范围 再次输入一个数字: //程序会再次提示用户 -1 //但现在程序现在不会打印超出范围 / 如何让程序提示用户再次输入数字并制作 我的课程更短 /
答案 0 :(得分:7)
你应该熟悉一个while循环。
只要条件在每次迭代后保持为真,它就会循环。
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("Enter Child's number(s) of Days: ");
int AGE = scan.nextInt();
if (AGE == 0 || AGE == 1) {
System.out.println("Classification: New Born");
} else if (AGE >= 2 && AGE <= 10) {
System.out.println("Classification: Infant");
} else if (AGE > 9 && AGE < 19) {
System.out.println("Classification: New Born");
} else if (AGE > 17 && AGE < 37) {
System.out.println("Classification: TODDLER");
} else if (AGE > 36 && AGE < 120) {
System.out.println("Classification: KID");
} else {
System.out.println("Classification: Out of Range");
}
}
另外,Java约定是用大写字母(child - &gt; Child)启动类名。
答案 1 :(得分:4)
public class child {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int AGE;
while(true){
System.out.println("Enter Child's number(s) of Days: ");
try {
AGE = scan.nextInt();
} catch (Exception e) {
System.out.println ("Please enter a number!");
}
if (AGE == 0 || AGE == 1){
System.out.println("Classification: New Born");
}
else if (AGE >= 2 && AGE <= 10){
System.out.println("Classification: Infant");
}
else if (AGE > 9 && AGE < 19){
System.out.println("Classification: New Born");
}
else if (AGE > 17 && AGE < 37){
System.out.println("Classification: TODDLER");
}
else if (AGE > 36 && AGE < 120 ) {
System.out.println("Classification: KID");
}
else{
System.out.println("Classification: Out of Range");
}
}
}
}
希望这有帮助。