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

Rag*_*ena 0 java

我正在编写一个简单的程序,当年龄小于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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

SHG*_*SHG 6

在构造函数中,无论到什么年龄,你的设置age0.它不在else声明中.用括号包裹它.

  • **即使您认为没有必要,也始终**使用括号.这种简单的习惯可以避免这种不必要的麻烦. (3认同)