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