Raghu Varma Manthena
Raghu Varma Manthena

Reputation: 95

Java code skipping the first if condition and is skipping over the others

I am writing a simple program that produces a certain out put when age is less than 13, between 13 and 18 and over 18. My code does not read past the first if statement and I don't know what I am doing wrong.

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();
        }
    }

Upvotes: 0

Views: 2116

Answers (1)

SHG
SHG

Reputation: 2616

In the constructor, regardless to what's the age, you're setting age to 0. It' not inside the else statement. Wrap it with brackets.

Upvotes: 6

Related Questions