Hello! How to get a size for an array of objects from a passed to the paramer Sc
ID: 640769 • Letter: H
Question
Hello! How to get a size for an array of objects from a passed to the paramer Scanner object. Suppose I have the textfile which has lines:
A B 2 midterm 100
C D 1 final 90
C D 1 midterm 90
A B 2 final 80
**NO ARRAYLIST IS ALLOWED!** And the textfile is passed into the method. How to get the size for the array non-randomly inside the method from the passed Scanner file?? What if you have infinite numbers of lines, so how could that be done?
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[s.nextInt()];
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();
}
Exam object = new Exam[s.nextInt()];
Exam object[index] = new Exam(firstName, lastName, ID, examTypeCasted, score);
//System.out.println();
index++;
}
readExam(s);
return object;
}
Explanation / Answer
The exam function can be written as:
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)
{
Exam[] object=new Exam[12];
for(int i=0;i<object.length;i++)< span=""></object.length;i++)<>
{
while(s.hasNext())
{
object[i]=s.next();
}
}
return object;
}
To get a size for an array of objects:
Exam[] object=new Exam[12];
System.out.println(Exam.size());
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.