如何从传递的对象获取数组的大小。在下面的代码中,我创建了一个大小为10的对象,因为传递的Scanner对象有10行对象。但如果传递了100个物体呢? 1000?怎么处理?例如:
public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
char examTypeCasted;
int score = 0;
int index = 0;
Exam[] object = new Exam[10];
while(s.hasNext())
{
//Returns firtsName and lastName
firstName = s.next();
lastName = s.next();
//Returns ID number
if(s.hasNextInt())
{
ID = s.nextInt();
}
else
s.next();
//Returns examType which is 'M' or 'F'
examType = s.next();
examTypeCasted = examType.charAt(0);
if(s.hasNextInt())
{
score = s.nextInt();
}
object[index] = new Exam(firstName, lastName, ID, examTypeCasted, score);
//System.out.println();
index++;
}
readExam(s);
return object;
答案 0 :(得分:1)
使用动态增长的数据结构而不是数组:
ArrayList<Exam> object = new ArrayList<Exam>();
然后改变:
object[index] = new Exam(firstName, lastName, ID, examTypeCasted, score);
要:
object.add( new Exam(firstName, lastName, ID, examTypeCasted, score) );
您还需要将退货类型更改为ArrayList<Exam>
,并且不要忘记导入它:
import java.util.ArrayList;
答案 1 :(得分:1)
如果您无法使用ArrayList
,则可以将代码更改为:
if (index == object.length) {
Exam objectTmp[] = new Exam[object.length * 2];
System.arraycopy(object, 0, objectTmp, 0, object.length);
object = objectTmp;
objectTmp = null;
}
object[index] = new Exam(firstName, lastName, ID, examTypeCasted, score);
如果object
数组已满,则策略是将其长度加倍。