Please help with question! I have to import a .txt file into my java program, re
ID: 3568483 • Letter: P
Question
Please help with question!
I have to import a .txt file into my java program, read it, and then find the average of the integers that are given. Here is what the file looks like:
Below each name is the individual's "scores" for a game. I have to average these scores, not including the -1 (this signals end of user's scores). I also have to include the user's name next to their score.
Here's what I have so far:
public static void main(String[] args) throws IOException{
File inputFile = new File("input.txt");
int sum = 0, count = 0;
Scanner in = new Scanner(inputFile);
while (in.hasNext()){
String name = in.nextLine();
System.out.println(name);
while (in.next() != "-1"){
int n = in.nextInt();
sum = sum + n;
count++;
}
}
int average = sum/count;
System.out.println(average);
This hasn't been working though. Whenever I run it, it says: "InputMismatchException." Is there a way to separate the name from the integers so that I can calculate the average for these scores?
Explanation / Answer
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileAverage {
public static void main(String[] args) throws IOException{
File inputFile = new File("D:/input.txt");
int sum = 0, count = 0;
Scanner in = new Scanner(inputFile);
String name = null,name1=null;
while (in.hasNext()){
try{
name=in.nextLine();
int n=Integer.parseInt(name);
while (n!=-1){
sum = sum + n;
count++;
n=Integer.parseInt(in.next());
}
int average = sum/count;
System.out.println(name1+" has an average :"+average);
}
catch(Exception ne)
{
name1=name;
}
}
}
}
o/p:
Rory Williams has an average :86
James Barnes has an average :79
Sarah Jane Smith has an average :82
Jack Sparrow has an average :68