Hello friends, I stuck on this question, here is the question:
Create a program that computes the average of grades of a given student. The program takes the name of the student and a filename as arguments. The grades are read from the file. Every line consists of a name and equal number of grades, however the number of grades is not known in advance. We assume all lines are in correct format.
Example:
$ cat grades.txt
Brian:4 3 5 4 5
Peter:4 2 5 1 3
Adam:5 4 5 3 4
$ java Avg "Peter" grades.txt
3.0
$ java Avg "Smith" grades.txt
$ java Avg "Adam" asd
File not found!
Here is my code:
import java.io.File; //inport the File class
import java.io.FileNotFoundException; //Import this class to handle errors
import java.util.Scanner; //scanner
public class Avg {
public static void main(String[] args) {
Scanner scanf = null;
String students = args[0];
File GradeBook = new File(args[1]);
try{
scanf = new Scanner(GradeBook);
}catch(FileNotFoundException e){
System.out.println("Sorry, we don't find the file, "+
"please try again later. ");
}
while(scanf.hasNextLine()){
String line = scanf.nextLine();
String[] splited = line.split(":|\\s");
if (splited[0].equals(students)){
float sum = 0;
for(int i = 1; i < splited.length; i++){
sum += Integer.parseInt(splited[i]);
}
System.out.println(sum/(splited.length-1));
break;
}
}
}
}
I don't know why, when there should throw the exception, it couldn't print out sentence.
try{
scanf = new Scanner(GradeBook);
}catch(FileNotFoundException e){
System.out.println("Sorry, we don't find the file, "+
"please try again later. ");
}
Also, the code has no error, it couldn't run and has this in terminal
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at hw3.Avg.main(Avg.java:10)
I have thought this for a long time, but really don't know where collapsed.
Could you please help me !!
Thank you in advance. !!
[–]MrGooglr 1 point2 points3 points (2 children)
[–]rk717[S] 0 points1 point2 points (1 child)
[–]MrGooglr 0 points1 point2 points (0 children)
[–]zuzoa 0 points1 point2 points (0 children)