我正在尝试制作一个简单的程序,演示如何使用对象的ArrayLists。我希望能够输入要存储在对象中的细节以及搜索和打印对象。
我正在学习这项课程我已经完成了我的学生课程,并且我已经开始了我的studentTest课程,但我正在寻找输入的帮助。
这是我到目前为止所做的:
package student;
public class Student {
private String studentName;
private String studentNo;
private String email;
private int year;
public Student() {
/**studentName = null;
*studentNo = null;
*email = null;
*year = -1;
*/
}
public Student(String nName, String nNum, String nEmail, int nYr) {
this.studentName = nName;
this.studentNo = nNum;
this.email = nEmail;
this.year = nYr;
}
public void setStudentName(String newStudentName) {
studentName = newStudentName;
}
public void setStudentNo(String newStudentNo) {
studentNo = newStudentNo;
}
public void setEmail(String newEmail) {
email = newEmail;
}
public void setYear(int newYear) {
year = newYear;
}
public String getStudentName() {
return studentName;
}
public String getStudentNo() {
return studentNo;
}
public String getEmail() {
return email;
}
public int getYear() {
return year;
}
}
}
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class studentTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
}
}
答案 0 :(得分:1)
查看Scanner的文档。
从目前为止在studentTest
中完成的代码看来,您正在接受用户的所有输入。
您基本上需要在循环中输入所有数据:
// create ArrayList
for (int i=0; i < 5; i++) {
String studentName = input.nextLine();
....
Student student = new Student();
student.setStudentName();
...
// add student to arraylist
}
我认为你将从填补我遗漏的内容中受益。
答案 1 :(得分:0)
我认为他只想填写学生班 像这样的东西。
while(true){
Scanner input = new Scanner(System.in);
Student student1 = new Student();
int year= input.nextInt();
String studentName=input.nextLine();
studentNo=input.nextLine();
String email=input.nextLine();
student1.setStudentName(studentName);
student1.setStudentNo(studentNo);
student1.setEmail(email);
student1.setYear(year)
int year= input.nextInt();
String studentName=input.nextLine();
studentNo=input.nextLine();
String email=input.nextLine();
break; // at the last position
}
答案 2 :(得分:-1)
您可能需要更新主要方法,如下所示:
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
int countStudents = input.nextInt();
for(int i=0; i< countStudents; i++){
Student student = new Student();
System.out.println("Enter details for student"+i);
System.out.println("Enter name");
student.setStudentName(input.next());
System.out.println("Enter Number");
student.setStudentNo(input.next());
System.out.println("Enter email");
student.setEmail(input.next());
System.out.println("Enter year");
student.setYear(input.nextInt());
students.add(student);
}
//Your list of students is populated now
}