I have the following in a dat file:
Obe 20 12 15 20 -1
Twitter 16 12 18 19 -1
Karah 30 15 12 3 30 -1
Cappy 12 12 13 15 14 -1
Monkey 17 16 15 14 14 -1

I am trying to write a Java program to read information from the file, display the original information (one line for each person) along with the person's average and announce who is the highest average. I can't figure out how to get the average to work. I think because the dat file has both String values and int values, it doesn't allow me to do what I have below. Also I have no idea how to display the highest average or to display what I have above. Can anyone help?

import java.util.*;
import java.io.*;
import java.math.*;
import java.text.NumberFormat;		// Needed for number format class. 
import java.util.Scanner;			// Needed for the Scanner class.

public class NumberAnalysis
	{
		public static void main(String[] args) throws IOException
		{    
			String filename;		// To hold a filename.
			String first;
			int count = 0, num = 0;
			long sum = 0;
			double average = 0, square = 0;
			
			// Create a Scanner object to read input.
			Scanner keyboard = new Scanner (System.in);
			
			// Get the filename.
			System.out.print("Enter the filename: ");
			filename = keyboard.nextLine ( );
	
			// Open the file.
			FileReader freader = new FileReader(filename);
			BufferedReader inputFile = new BufferedReader(freader);
			
			// Read the first line from the file.
			first = inputFile.readLine ( );
			
			while (first != null)
			{
				Scanner fileScan = new Scanner (filename);
				while (fileScan.hasNext())
				{
					sum += fileScan.nextInt();
					count++;
				}
				
				average = (double) sum / (double) count;
				System.out.println("sum == "+sum);
				System.out.println("avg == "+average);
				
				first = inputFile.readLine( );
			}
			
			// Close the file.
			inputFile.close ( );
		}
		
	
    }

Recommended Answers

All 16 Replies

I assume here the numbers are the score over which you need to make an average, "-1" is the termination indicating character and the first string in a line is the name of the person.
Well, what you can do here is read all the lines entirely from the file one by one, into an array of Strings. And then split each string into an array of other strings that the line contains. In the second case the strings would be the name, scores and "-1". (I am assuming here that the format of the record remains same for any record) After you have done that, you can iterate through the second array collecting scores (currently strings) and converting them to 'int'. Once you have done that I suppose you can as easily perform the sum/average math over them.

Every line starts with a String. So read it in. Then use a while loop to read in each integer on the line until -1 is the last integer you read in. Then repeat this process until you are at the end of the file.

I'm sorry, but I've never used arrays. I'm a Java newbie. Could you explain further please.

// We define a string
String str = "olgratefuldead learns java";
// We use the split method of the String class to split the string on spaces.
String [] strArray = str.split(" ");
for(int i=0;i<strArray.length;i++){
    System.out.println(strArray[i]);
}

The output for the above code will be :
olgratefuldead
learns
java

The code above creates an array of Strings. An array is a collection of similar types. If you know String, it's quite simple to know arrays of Strings, it's just like multiple String objects put together one after another. You can learn more about arrays in Java here

I have tried what you said and I can't figure out how to extract the numbers to convert them to integers from the list below:

Obe
20 12 15 20
-1
Twitter
16 12 18 19
-1
Karah
30 15 12 3 30
-1
Cappy
12 12 13 15 14
-1
Monkey
17 16 15 14 14
-1


My code is here:

import java.util.*;
import java.io.*;
import java.math.*;
import java.text.NumberFormat;		// Needed for number format class. 
import java.util.Scanner;			// Needed for the Scanner class.

public class NumberAnalysis
	{
		public static void main(String[] args) throws IOException
		{    
			String filename;		// To hold a filename.
			String first;
			int count = 0, num = 0;
			long sum = 0;
			double average = 0, square = 0;
			FileInputStream fis = null;
			boolean validInput = true;

			
			// Create a Scanner object to read input.
			Scanner keyboard = new Scanner (System.in);
			
			
			
			do
			{
				
				// Get the filename.
				System.out.print("\nEnter the filename: ");
				filename = keyboard.nextLine ( );
			try 
				{
					// Open file.
					fis = new FileInputStream(filename);
					validInput = false;
				}
			catch (FileNotFoundException exception)
				{
					System.out.println("\nThe file was not found. Please input a valid file");
					
				}
			
			}while(validInput);
			  
			// Open the file.
			FileReader freader = new FileReader(filename);
			BufferedReader inputFile = new BufferedReader(freader);
			
			// Read the first line from the file.
			first = inputFile.readLine ( );
			
			while (first != null)
			{
				String [] strArray = first.split("	");
				for(int i=0;i<strArray.length;i++)
				{
					System.out.println(strArray[i]);
				}
				
				first = inputFile.readLine( );
			}
		
	
			
			
		}
		
	
    }

To explain, lets take one of the records you have mentioned. Say "Obe 20 12 15 20 -1", this is the first line in your file. When you do:

first = inputFile.readLine ( );

first contains the entire line "Obe 20 12 15 20 -1"

After that when you do:

String [] strArray = first.split(" ");

The array contains:
strArray[0] = "Obe"
strArray[1] = "20"
strArray[2] = "12"
strArray[3] = "15"
strArray[4] = "20"
strArray[5] = "-1"

Now when you already know this format, you can start converting the strings from index 1 to 4 of the array doing:

int [] scores = new int [4];
int j=0;
for (int i=1;i<(strArray.length-1);i++){
    // you begin i from 1 since at index 0 you have the name
    // you end the loop when i equals one less than array length since the last integer is always going to be -1, you don't need to bother  parsing this.
    scores[j++] = Integer.parseInt(strArray[i]);
}

Now you have all the scores for "Obe" in the scores array, you can proceed to doing the sum/average math on it like you would have done with regular integers.

I can't figure out where to put the iteration. I tried throughout the while loop. And how does the iteration realize which strings to grab per line? Thanks.

If you read my previous post carefully, I have shown the iteration being done after the line has been read from the file and after it has been splitted to get a string array.

Ok so I believe that I did what you said. My code is below. It compiles ok but it gives the following when I load my input file:

Obe
20
12
15
20
-1
Twitter
16
12
18
19
-1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
	at NumberAnalysis.main(NumberAnalysis.java:63)
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.NumberFormat;		// Needed for number format class. 
import java.util.Scanner;			// Needed for the Scanner class.

public class NumberAnalysis
	{
		public static void main(String[] args) throws IOException
		{    
			String filename;		// To hold a filename.
			String first;
			int count = 0, num = 0;
			long sum = 0;
			double average = 0, square = 0;
			FileInputStream fis = null;
			boolean validInput = true;
			
			
			// Create a Scanner object to read input.
			Scanner keyboard = new Scanner (System.in);
			
			
			
			do
			{
				
				// Get the filename.
				System.out.print("\nEnter the filename: ");
				filename = keyboard.nextLine ( );
				try 
				{
					// Open file.
					fis = new FileInputStream(filename);
					validInput = false;
				}
				catch (FileNotFoundException exception)
				{
					System.out.println("\nThe file was not found. Please input a valid file");
					
				}
				
			}while(validInput);
			
			// Open the file.
			FileReader freader = new FileReader(filename);
			BufferedReader inputFile = new BufferedReader(freader);
			
			// Read the first line from the file.
			first = inputFile.readLine ( );
			
			
			
			while (first != null)
			{
				String [] strArray = first.split("	");
				int [] scores = new int [4];
				int j=0;
				for (int i=1;i<(strArray.length-1);i++)
				{
					scores[j++] = Integer.parseInt(strArray[i]);
				}
				for(int i=0;i<strArray.length;i++)
				{
					System.out.println(strArray[i]);
				}
				
				first = inputFile.readLine( );
				
			}
			
			
			
			
		}
		
		
    }
int [] scores = new int [4];

You declare your scores array to be of size 4. And you put all the things from index 1 to index length-1 of strArray into the scores array. So, in essence, your strArray should contain no more than 4+2 i.e 6 elements. And according to the current format we assumed that should be the case, that is the reason I told you that I assume the format is the same for all. Now if some of your records are going to contain more than 6 elements, or more appropriately, more than 4 scores you should declare scores array in this way:

int [] scores = new int [strArray.length-2];

This will ensure that you never run out of bounds with the scores array.

Ok that makes much more sense. Now since these are now in the scores array, shouldn't I be able to access them by doing System.out.println("Element at index 1: " + scores[1]); The compiler gives me

NumberAnalysis.java:73: cannot find symbol
symbol  : variable scores
location: class NumberAnalysis
			System.out.println("Element at index 1: " + scores[1]);

Any ideas?

You have code that says: validInput = false; Then you said while (validInput), which will never execute because you previously set validInput to false. So no, nothing was ever read into your scores array as far as I can tell.

Actually when I input the file without System.out.println("Element at index 1: " + scores[1]); it gives me

Obe
20
12
15
20
-1
Twitter
16
12
18
19
-1
Karah
30
15
12
3
30
-1
Cappy
12
12
13
15
14
-1
Monkey
17
16
15
14
14
-1

Which is halfway to what I need. Unless I'm confused...the scores line just takes and throws them into an array after converting them into integers.

The code you have posted earlier does not contain this anywhere

System.out.println("Element at index 1: " + scores[1]);

So post the new code again. Also I am obeserving that even after so many posts you aren't taking much from them. Read the posts carefully, it isn't much difficult a task and you have been already given enough pointers but you don't seem to learning much from them. It would help to learn one thing that we aren't going to spoon feed anyone here, giving him the code in parts one by one explaining everything to him one at a time, we need to see some effort better than this from you.

@BestJewSinceJC : Yes you have a point there, that when you declare a variable false a while condition checking that variable will never enter the loop, but the problem he mentions - "cannot-find-symbol" will not be caused by that anyway. Why it does cause can only be told when he posts his new code.

commented: Very helpful +1

I'm just getting a crash course in arrays and how strings relate to them. I'm ex I'm not trying to get spoonfed the solution. I appreciate your help and I've left you positive feedback. Anyways...if you want to help, below is what I have done since the last post. I think that I have a logical error while incrementing the scores:

import java.util.*;
import java.io.*;
import java.math.*;
import java.text.NumberFormat;		// Needed for number format class. 
import java.util.Scanner;			// Needed for the Scanner class.
import java.text.DecimalFormat;


public class NumberAnalysis
	{
		public static void main(String[] args) throws IOException
		{    
			String filename;		// To hold a filename.
			String first;
			int count = 0, sum = 0;
			double average = 0, square = 0;
			FileInputStream fis = null;
			boolean validInput = true;
			
			
			// Create a Scanner object to read input.
			Scanner keyboard = new Scanner (System.in);
			
			
			
			do
			{
				
				// Get the filename.
				System.out.print("\nEnter the filename: ");
				filename = keyboard.nextLine ( );
				try 
				{
					// Open file.
					fis = new FileInputStream(filename);
					validInput = false;
				}
				catch (FileNotFoundException exception)
				{
					System.out.println("\nThe file was not found. Please input a valid file");
					
				}
				
			}while(validInput);
			
			// Open the file.
			FileReader freader = new FileReader(filename);
			BufferedReader inputFile = new BufferedReader(freader);
			
			// Read the first line from the file.
			first = inputFile.readLine ( );
			
			
			
			while (first != null)
			{
				String [] strArray = first.split("	");
				int [] scores = new int [strArray.length];;
				int j=0;
				for (int i=1;i<(strArray.length-1);i++)
				{
					scores[j++] = Integer.parseInt(strArray[i]);
				}
				for(int i=0;i<strArray.length;i++)
				{
					
					System.out.println(strArray[i]);
			
				}
				
				first = inputFile.readLine( );

			
				
				scores = scores++;
				
				System.out.println ();
				
				if (count == 0)
					System.out.println ("No values were entered.");
				else
				{
					average = (double)sum / scores;
					
					DecimalFormat fmt = new DecimalFormat ("0.###");
					System.out.println ("The average is " + fmt.format(average));
				}
				
				

				System.out.println(sum);
				
				
				
			}
			
			
		}
		
		
    }
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.