我只是Java的初学者,我正在尝试创建一个程序,显示多个对象的名称,年龄和出生年份。是否可以使用switch语句来获得这两个对象的出生年份?请把你的答案作为我的基本答案。谢谢。这是我的代码;
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);
}
}
答案 0 :(得分:0)
你说这一切都错了......你的变量,类,包都应该是可读的和有代表性的。您也想使用封装和适当的方法。此外,您正在存储一个易于计算的字段。我真的不确定switch语句试图实现什么。
此外,使用类中的控制台将其绑定到输出,而是返回一个String并从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;
}
}