我无法理解代码有什么问题。该方法返回Exam类型的对象数组。方法readAllExams从Scanner中提取标记并使用它们创建Exam对象。 Exam对象以数组形式返回。请帮忙吗?
public Exam(String firstName, String lastName, int ID, String examType, int score) {
this.firstName = firstName;
this.lastName = lastName;
this.ID = ID;
this.examType = examType;
this.score = score;
}
public static Exam[] readAllExams(Scanner s) {
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
int score = 0;
Exam[] object = new Exam[5];
while(s.hasNext()) {
firstName = s.next();
lastName = s.next();
if(s.hasNextInt()) {
ID = s.nextInt();
} else {
s.next();
}
examType = s.next();
if(s.hasNextInt()) {
score = s.nextInt();
}
object[] = new Exam(firstName, lastName, ID, examType, score);
return object;
}
}
答案 0 :(得分:1)
我认为你的代码应该是:
public static Exam[] readAllExams(Scanner s)
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
int score = 0;
Exam[] object = new Exam[5];
int index = 0; //new added code
while(s.hasNext())
{
// ........... your code ..........
object[index++] = new Exam(firstName, lastName, ID, examType, score);
}
return object; //return should be out of while loop to return an array
}
答案 1 :(得分:0)
object[]
不是索引数组的有效方法。
为了分配数组的元素,您需要知道哪个元素。例如,object[0]
是第一个元素。 object[4]
是第5个元素。 object[index]
是index
包含0的第一个元素,index
包含1的第二个元素,index
包含2的第三个元素等等...
填写数组时,常见的事情是保留一个计数器,存储您当前正在填写的索引 - 例如:(为简洁起见,删除了大部分代码)
int currentIndex = 0;
while(...) {
...
object[currentIndex] = ...;
currentIndex = currentIndex + 1; // or currentIndex += 1; or currentIndex++;
}