在第 4 步,我必须使用 4 个输入的信息项返回一个匿名实例化的 Student 对象。由于我找不到任何解决此问题的论坛,因此我需要一些设置帮助或示例。
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();
temp[i] = getStudent(); // Step 2
}
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 ___________________________________________________; // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(______); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
最佳答案
简单
return new Student(constructor args);
其中构造函数参数
是您的Student
构造函数所需的任何参数。
这里使用的“匿名”不是标准的 Java 术语。我想,由于您没有将对象引用分配给局部变量,因此可以将其视为“匿名”。由于 getStudent()
是在 getStudents()
at
temp[i] = getStudent();
因此引用将立即保存(到数组中)。
“匿名”出现在术语“匿名子类”中,但这是一个完全不同的概念,您可能还没有接触过。
关于java - 如何在java中返回匿名实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440248/