Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Help in text files and arrays in Java I want to know how to average numbers from

ID: 3569626 • Letter: H

Question

Help in text files and arrays in Java

I want to know how to average numbers from a text file and store them in an array. I want to find the average from 1 -4 is Jan and find the average from 5 -7 is Feb.

The num.txt file contains:

1 20
2 30
3 40
4 50
5 60

6 70

7 80

This is what I got so far

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

public class ReadFiles
{
   private int average;
   public static void main(String[] args) throws IOException
   {
       ReadFiles x = new ReadFiles();
       x.readNumbers();
   }
  
   public void readNumbers()
   {
       String fileName = "num.txt";
       Scanner inputStream = null;

       try
       {
           inputStream = new Scanner (new File(fileName));
       }
       catch(FileNotFoundException e)
       {
           System.out.println("Error opening the file " + fileName);
           System.exit(0);
       }
      
       while(inputStream.hasNextLine())
       {
           String line = inputStream.nextLine();
           String[] array = line.split(" ");
           System.out.println(array[1]);

       }

       inputStream.close();
          
   }

}

Explanation / Answer

package q343;

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

public class ReadFiles{
private int average;
public static void main(String[] args) throws IOException
{
ReadFiles x = new ReadFiles();
x.readNumbers();
}

public void readNumbers()
{
String fileName = "num.txt";
Scanner inputStream = null;

try
{
inputStream = new Scanner (new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}

//---------------------------------changed from here---------------------------------------------//

String line = new String();
int num;
int sum=0,count=0;
int average;
while(inputStream.hasNextLine())
{
line = inputStream.nextLine();
num = Integer.parseInt(line.split(" ")[1]);
sum+=num;
count++;
}

average = sum/count;
System.out.println("Average: " + average);

//-----------------------------------------upto here--------------------------------------------//
inputStream.close();

}

}