Multiple Objects in One Switch; is it possible?

237 Views Asked by At

Im just a beginner in Java and i'm trying to create a program that will display the name, the age, and the year of birth for multiple objects. Is it possible if I will use switch statement to have the year of birth for these two objects? Please make your answer as basic as mine. Thanks. Here is my code;

package PackageOne;
public class NewClass {

 static String name;
 static int age = 0;
  static int currentYear = 2015;
 static int birth;

 public static void main (String []args){

      NewClass person1 = new NewClass("Ichiro ", 15);
      NewClass person2 = new NewClass("Marie ", 21);
      person1.getInfo();
      person2.getInfo();
     birth = currentYear - age;

switch(birth){
    case 1: birth = 2000;
        break;
    case 2: birth = 2001; break;
    case 3: birth = 2002;break;
    default: System.out.println(birth);break;

}
 }
public NewClass(String x, int y){
   this.name = x;
   this.age = y;
}
public void getInfo(){
    System.out.println(name + age);
}
 }
1

There are 1 best solutions below

0
On

You're going about this all wrong... Your variables, classes, packages should all be readable and representative. You want to use encapsulation and proper methods also. Also, you're storing an easily calculable field. I'm really not sure what the switch statement was trying to achieve.

Also, using the console from within a class ties it to an output, rather return a String and print it from main.

package com.denmark16;


public class Person {

      // Fields are private, and thus encapsulated
      private static String _name;
      private static int _age;


      // I'd put main in another class to make it tidier, but it's ok here
      public static void main (String []args){

          //By using a list, you can add as many people as you wish
          ArrayList<Person> people = new ArrayList<Person>();

          people.add(new Person("Ichiro ", 15));
          people.add(new Person("Marie ", 21));


      for (Person person in people) {
               System.Console.writeLine(getDetails(new DateTime().year()));
          }

     }


    // Not sure why you'd store age, I'm guessing it's an exercise, but really it should be Date of Birth
    public Person(String name, DateTime age){
       _name = name;
       _age = age;
    }


    // This should probably be a toString with hashCode
    public string getAllDetails(int year){
        return _name + " " + _age + " " + getYearOfBirth(new DateTime().getYear());
    }


    // This is flaky as really, we should store and calculate against the Date of Birth
    public int getYearOfBirth(int year) {
        return year - _age;     

    }

}