Question

I am trying to get the averages of values in a text file. The content of the file is:

Agnes 56 82 95 100 68 52
Bufford 87 92 97 100 96 85 93 77 98 86
Julie 99 100 100 89 96 100 92 99 68
Alice 40 36 85 16 0 22 72
Bobby 100 98 92 86 88

I have to skip the names, and try to sum the values of the integers of each line. The ouput should be something like this:

Agnes, average = 76
Bufford, average = 91
Julie, average = 94
Alice, average = 39
Bobby, average = 93

My problem is that i am unable to sum the values (using sum+=sc1.nextInt()). I also cant count the number of tokens of just the integers. For example, for the first line I need countTokens to equal 6, but i get 7, even after I skip the name.

import java.io.*; 
import java.util.*; 
public class studentAverages
{
public static void main() throws IOException
{
    Scanner sf = new Scanner(new File("C:\\temp_Name\\StudentScores.in"));
    int maxIndex = -1; 
    String text[] = new String[100]; 
    while(sf.hasNext( ))
    {
        maxIndex++;
        text[maxIndex] = sf.nextLine();
    }
    sf.close();

    int sum=0;
    int avg=0;
    int divisor=0;
    for (int i=0;i<=maxIndex; i++)
    {
        StringTokenizer sc= new StringTokenizer(text[i]);
        Scanner sc1= new Scanner (text[i]);

        while (sc1.hasNext())
        {
            sc1.useDelimiter(" ");
            sc1.skip("\\D*");                
            System.out.print(sc1.nextInt());
            System.out.println(sc1.nextLine());
            sum+=sc1.nextInt(); // trying to sum all the numbers in each line, tried putting this line everywhere
            avg=sum/divisor;
            break;
        }            
        System.out.println(avg);
        while (sc.hasMoreTokens())
        {         
            divisor=sc.countTokens()-1; //Not able to count tokens of just the numbers, thats why I am using -1 
            //System.out.println(divisor);
            break;
        }
    }
    //this is for the output 
    /*for (int i=0; i<=maxIndex; i++)
    {
        String theNames="";
        Scanner sc= new Scanner (text[i]);
        theNames=sc.findInLine("\\w*");
        System.out.println(theNames + ", average = ");
    }*/
}
}
Was it helpful?

Solution 2

Try this one:

    Scanner scanner = new Scanner(new File("resources/abc.txt"));
    //check for next line
    while (scanner.hasNextLine()) {
        //create new scanner for each line to read string and integers
        Scanner scanner1 = new Scanner(scanner.nextLine());
        //read name
        String name = scanner1.next();
        double total = 0;
        int count = 0;
        //read all the integers
        while (scanner1.hasNextInt()) {
            total += scanner1.nextInt();
            count++;
        }
        System.out.println(name + ", average = " + (total / count));
    }
    scanner.close();

output:

Agnes, average = 75.5
Bufford, average = 91.1
Julie, average = 93.66666666666667
Alice, average = 38.714285714285715
Bobby, average = 92.8

--EDIT--

Here is the code as per your last comment (I have to use StringTokenizer`/string methods like useDelimiter, skip, etc to arrive at the answer)

    Scanner sf = new Scanner(new File("resources/abc.txt"));
    List<String> text = new ArrayList<String>();
    while (sf.hasNext()) {
        text.add(sf.nextLine());
    }
    sf.close();

    for (String str : text) {
        StringTokenizer sc = new StringTokenizer(str, " ");
        double sum = 0;
        int count = 0;
        String name = sc.nextToken();
        while (sc.hasMoreElements()) {
            sum += Integer.valueOf(sc.nextToken());
            count++;
        }
        System.out.println(name + ", average = " + (sum / count));
    }
}

output

Agnes, average = 75.5
Bufford, average = 91.1
Julie, average = 93.66666666666667
Alice, average = 38.714285714285715
Bobby, average = 92.8

OTHER TIPS

I would recommend splitting each line using the split method and then looping through those values while ignoring the first, because you know that is the title.

public static void main() throws IOException {
    Scanner sf = new Scanner(new File("C:\\temp_Name\\StudentScores.in"));
    int maxIndex = -1; 
    String text[] = new String[100]; 

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

    sf.close();

    for(int i = 0; i < maxIndex; i ++) {
        String[] values = text[i].split(" ");
        String title = values[0];
        int sum = 0;

        for(int j = 1; i < values.length; j ++) {
            sum += Integer.parseInt(values[j]);
        }

        double average = sum / (values.length - 1);
        System.out.println(title + ": " + average);
    }
}

Notice that the inner loop's index begins at 1 and not 0, and that when calculating the average, we subtract one from the size of the values array because we want to ignore the title.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top