gpt4 book ai didi

Java 代码跳过第一个 if 条件并跳过其他条件

转载 作者:行者123 更新时间:2023-12-01 07:48:25 25 4
gpt4 key购买 nike

我正在编写一个简单的程序,当年龄小于 13 岁、13 岁至 18 岁之间以及 18 岁以上时,该程序会产生特定的输出。我的代码不会读取第一个 if 语句,并且我不知道我在做什么错了。

import java.io.*;
import java.util.*;
public class Person {
public int age;

public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if (initialAge>-1){
age=initialAge;
}
else
System.out.println("Age is not valid, setting age to 0. ");
age=0;
}

public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
if(age<13)
System.out.println("You are young.");


else if(age>=13&&age<18)
System.out.println("You are a teenager.");

else
System.out.println("You are old.");


}

public void yearPasses() {
// Increment this person's age.
age++;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}

最佳答案

在构造函数中,无论年龄是多少,您都将 age 设置为 0。它不在 else 语句内。用括号括起来。

关于Java 代码跳过第一个 if 条件并跳过其他条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44379627/

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