我试图在temp数组中分配当前数组元素,并在调用getStudent方法后返回Student对象....我调用了getStudent方法(步骤2)并且有temp [i] =分配临时数组中的当前元素但无法弄清楚它应该是什么=将它与返回的Student对象配对。当使用getStudent()并运行程序时,输出是输入学生数,用户输入数字,这就是发生的一切,它不要求用户输入名称等,我不是确定第2步是问题还是完全存在其他问题。
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
答案 0 :(得分:1)
首先问题是第一个问题:
temp = new Student[input.nextInt()];
在该行中,您已经要求用户输入了多少学生并将其存储在how_many
中。所以我假设您想改为:
temp = new Student[how_many];
我在评论中也说过:
但是,请同时查看您的private static void printStudents(Student[] s)
方法,然后在线上//第6步我不相信您希望这样做。相反,您希望System.out.println(s[i]);
不是System.out.println(getStudent());
我的代码替换可以工作,但您需要覆盖toString方法,以便它实际显示信息