【发布时间】:2021-05-09 03:21:48
【问题描述】:
我有一个学生类,它由名字和姓氏方法和构造函数组成。我需要创建一个传递控制台输入并将其分配给学生对象的方法,并且可以在 main 方法中分别打印全名和名字。
学生班
public class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public String toString(){
return firstName + " " + lastName;
}
}
学生姓名班级
import java.util.Scanner;
public class StudentName {
public static void main(String[] args) {
System.out.println("Your full name is " + getStudentFullName(newStudent));
System.out.println("Your first name is " + getStudentFullName(firstName));
}
public static void getStudentFullName(Student student){
Scanner sc = new Scanner(System.in);
System.out.print("What is your full name?");
String name = sc.nextLine();
name = name.trim();
int index1 = name.indexOf(" ");
String firstName = name.substring(0,index1);
String lastName = name.substring(index1 + 1);
Student newStudent = new Student(firstName,lastName);
}
}
更新:错误消息
error: cannot find symbol
System.out.println("Your full name is " + getStudentFullName(newStudent));
symbol: variable newStudent
location: class StudentName
error: cannot find symbol
System.out.println("Your first name is " + getStudentFullName(firstName));
symbol: variable firstName
location: class StudentName
【问题讨论】:
-
complete 错误信息是什么?请在您的问题中包含所有相关详细信息。
-
@StephenC 添加错误。
-
OK ... 那么为什么在
getStudentFullName中声明newStudent?在你使用它的方法中声明它。同样,你为什么在main中使用firstName?它没有在main中声明。 -
另外...查看
getStudentFullName并了解其用途。然后问自己,为什么要打印getStudentFullName的>>结果 -
我建议您阅读Rubber Duck Debugging。这是一种涉及阅读您自己的代码并理解它的技术……通过尝试向(想象中的)其他人解释它。