我正在尝试将按钮链接到方法,用户必须在其中输入名称,GPA和ID。 这是代码
在主要方法中:
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = txt2.getText();
String ID = txt2.getText();
String GPA = txt3.getText();
addNewStudent();
} });
同一类中的方法
public static void addNewStudent() {
String name =
String IDnum = scanner.nextLine();
String GPA = scanner.nextLine();
Student newStudent = Student.createStudent(name, IDnum, GPA);
if (studentInfoSystem.addNewStudent(newStudent)) {
System.out.println("New student added: name = " + name + ", ID = " + IDnum + " GPA: " + GPA);
} else {
System.out.println("Cannot add, " + name + " already on file");
}
}
我想知道如何连接它们。
在添加新学生中使用参数,然后将其分配给变量
So, apparently, you are not familiar with the concept of method parameters.
如果要将信息获取到方法中,则必须将该信息作为参数传递。而不是像这样声明您的方法:
您可以这样声明:
This method signature means that when you call
addNewStudent()
, you have to give it three arguments of type String, like this:Then, inside
addNewStudent()
, you can do whatever you want with those passed arguments:一些建议:Java区分大小写。通常,您使用小写字母命名变量,对于变量名称中的所有新单词都使用大写字母。在了解发生了什么之前,不要超越自己,尝试做事。您对Java的掌握充其量似乎很薄弱。花些时间研究我上面链接的教程,您将发现您不再需要提出这类基本问题。