包括以下内容:
这是我到目前为止所做的:
public class Student
{
//the student's full name
String FirstName;
String LastName;
/**
* Create a new student with a given name a
*/
public Student(String name)
{
FirstName = name;
LastName = name;
}
/**
* Return the first name of this student
*/
public String getFirstName()
{
return FirstName;
}
/**
* Return the last name of this student
*/
public String getLastName()
{
return LastName;
}
public static void main(String[] args)
{
//gives a name to the students
Student FirstName = new Student("Samantha");
Student LastName = new Student("Jones");
//each object calls the getName method
System.out.println("The students first name is: " +Student.getFirstName());
System.out.println("The students last name is: " +Student.getLastName());
}
}
答案 0 :(得分:1)
您创建了一个新对象,但以后不再使用它。
您应该在Student构造函数中为lastname添加第二个参数:
public Student(String firstname, String lastname)
{
FirstName = firstname;
LastName = lastname;
}
主要是在创建后使用你的学生对象。
public static void main(String[] args)
{
//gives a name to the students
Student stud1 = new Student("Samantha", "Jones");
Student stud2 = new Student("Timo", "Hantee");
//each object calls the getName method
System.out.println("The students first name is: " + stud1.getFirstName());
System.out.println("The students last name is: " + stud2.getLastName());
}
答案 1 :(得分:1)
替换为:
public Student(String _firstname, String _lastname)//constructor header
{
FirstName = _firstname;//description of constructors
LastName = _lastname;
}
答案 2 :(得分:0)
在您的Student Class中,FirstName和LastName是两个不同的变量,因此您需要在构造函数中为其指定不同的值。因此,使用一个参数创建构造函数,使用两个参数创建它,一个用于firstName,另一个用于lastName。如下所示:
public Student(String firstName, String lastName)//constructor header
{
this.firstName = firstName;//description of constructors
this.lastName = lastName;
}
public static void main(String[] args)
{
//gives a name to the students
Student student= new Student("Samantha", "Jones");
//each object calls the getName method
System.out.println("The students first name is: " +student.getFirstName());
System.out.println("The students last name is: " +student.getLastName());
}
在这里,我想再向您推荐一个对Java程序员来说非常重要的事情,遵循Java命名约定。变量名称应以小写字母开头。