So i have a problem that reads: Each line of the file consists of a student’s name followed by an unpredictable number of test
scores. The number of students is also unpredictable. The desired output is as shown where the
numbers there represent the average test score rounded to the nearest whole number.
Create a class called StudentAverages that will input the StudentScores.in text file and produce
the indicated output.
i attached the file that i have to read from.
My code so far is:

import java.io.*; 
import java.util.*; 
public class fdhg

{
public static void main(String args[]) throws IOException
    {
        Scanner sf = new Scanner(new File("Grades.txt"));
        int maxIndx = -1; 
        String text[] = new String[1000]; 

        while(sf.hasNext())
        {
            maxIndx++;
            text[maxIndx]=sf.nextLine();

        }
        sf.close();
        String answer="";
        int sum=0;
        double average=0;
        int n=0;
        String a="";
        for(int j=0;j<=maxIndx; j++)
        {
            Scanner sc=new Scanner(text[j]);

            sum=0;
            String s="";
            n=0;

            while(sc.hasNext())
            {
                int i=sc.nextInt();

                sum=sum+i;
                n=n+1;
            }
            average=sum/n;

            System.out.println(average);
        }


}

}

So i know how to get the averages if there were just numbers in the file but there is a name at the beginning. How do i print out their name with out having any idea what the contents of the file are. thanks for any help you can offer.

Dani AI

Generated

A simple way to handle an unknown count of scores per line is to scan each line twice: first gather the name (all tokens before the first integer), then consume all integer tokens to compute the average. This avoids assumptions about name length and relies on Scanner’s default whitespace delimiter and hasNextInt() to detect when scores begin. Remember to cast before dividing so you do not truncate with integer division, and round the result to the nearest whole number. See Scanner Javadoc and Math.round. Note that ordinary integer division truncates toward zero; casting to double prevents that (Math.floorDiv docs mention truncation).

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class StudentAverages {
  public static void main(String[] args) throws IOException {
    try (Scanner file = new Scanner(new File("Grades.txt"))) { // try-with-resources closes file
      while (file.hasNextLine()) {
        String line = file.nextLine().trim();
        if (line.isEmpty()) continue;

        try (Scanner t = new Scanner(line)) {
          StringBuilder name = new StringBuilder();
          while (t.hasNext() && !t.hasNextInt()) {
            if (name.length() > 0) name.append(' ');
            name.append(t.next());
          }
          long sum = 0; int count = 0;
          while (t.hasNextInt()) { sum += t.nextInt(); count++; }

          long avg = (count == 0) ? 0 : Math.round(sum / (double) count);
          System.out.println(name + " " + avg);
        }
      }
    }
  }
}

Tip: use try-with-resources to close scanners automatically (try-with-resources guide).

Recommended Answers

All 2 Replies

Reading the file with a Scanner is a good start. Now consider the format of you data: you have character strings separated by spaces. This means you could use the .split() method on spaces (" ") to break up your unknown number of scores into a String[]. Remember that the name will always be in index 0, so it will be easy to print. You then simply need to find the average of the rest of the entries in the array. You may need to use the Integer class' parseInt() method as these numbers will be encoded as strings.

Good luck!

ok thanks. regarding the split...im not sure where i should put it or how to how to split the line then convert them back into integers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.