所以我的Java老师想让我们编写一个简单的程序,简单地说"Ben Barcomb是19岁“--仅此而已,仅此而已。
他不像普通人一样使用System.out.println
,他希望我们在person类中为必须是private
的全名和年龄使用一个实例变量,他还希望为全名和变量使用getter和setter方法。这是我所拥有的测试代码,但我仍然停留在变量和getter/setter方法上。
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Bilal Gonen");
p1.setAge(76);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public Person(String aFullname)
{
myFullname = aFullname;
}
public void setFullname()
{
myFullname = aFullname;
}
}
发布于 2014-11-16 00:35:03
这里是一个getter和setter的例子。我相信你可以用这个做向导。
public class Person
{
private String firstName;
private String lastName;
public void setName(String f, String l)
{
firstName = f;
lastName = l;
}
public String getFirstName()
{
return firstName;
}
}
设置器和getter上的短tutorial。
发布于 2014-11-16 00:38:03
不为你做家庭作业,但我会为你提供一些帮助。下面是一个带有一个变量的person类示例,添加您自己需要的其他变量。
public class Person {
int age;
public void setAge(int age) { // notice how the setter returns void and has an int parameter
this.age = age; // this.age means the age we declared earlier, while age is the age from the parameter
}
public int getAge() { // notice the return type, int? this is because the var we're getting is an int
return age;
}
发布于 2014-11-16 01:09:30
感谢大家的帮助,以及我自己做的一些研究,我得到了程序来正确编译和运行,这是源代码。再次感谢大家的帮助!
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Ben Barcomb");
p1.setAge(19);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person
{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public void setAge(int newAge)
{
myAge = newAge;
}
public void setFullname(String aFullname)
{
myFullname = aFullname;
}
}
https://stackoverflow.com/questions/26952399
复制相似问题