6 Replies Latest reply: Jul 17, 2008 7:42 PM by 843785 RSS

    Reading numbers from a text file

    843785
      Yesterday I wrote up a program where it reads in a txt file with a list of numbers, and from there it outputs the highest number, lowest number and average of all the numbers. My code works for the most part except for one snag. It will not read a 0 by itself in the txt file. The list in the text file is this:

      10
      50
      100
      70
      200
      1000
      60
      30
      40
      0

      My program returns 1000 as the highest, but since it completely ignores zero, it lists ten as the lowest and gives me the average of nine numbers instead of ten. Whats even weirder is that if I change that zero to another number, my program outputs nothing. Any idea where I went wrong here? Any help would be appreciated.
      import java.util.Scanner;
      import java.io.File;
      import java.io.FileNotFoundException;
      import java.math.*;
      
      public class FileNumber
      {
          public static void main(String[] args)
          {
                int count = 0; 
                  double sum = 0; 
                  double max = 0; 
              double min = 0; 
              double next=0;
                  
                  
              System.out.print("Enter file name: ");
              Scanner keyboard = new Scanner(System.in);
              String fileName = keyboard.next();
              Scanner inputStream = null;
              System.out.println("The file " + fileName + " contains a list of numbers.");
                                       
             try
             {
                 inputStream = new Scanner(new File(fileName));
      
             }
                 catch(FileNotFoundException e)
             {
                 System.out.println("Error opening the file " + fileName);
                 System.exit(0);
             }
         
             while (inputStream.hasNextLine())
             {
                 for(int i=0; next >= 0; i++)
                      {
                       next = inputStream.nextDouble();
                              if(next > 0)
                              {
                                              
                                      count += 1; //keeps track of every entry
                                      sum += next; //adds up all the entries
                    
                                      if(next > max)//if the next entry is higher then the previous entry, the it become the new high entry
                                          {
                                          max = next;
                                          }
                                      
      
                                      if(i==0)
                                          {
                                          min = next;
                                          }
                                      
      
                                      if(next < min)//if the next entry is lower then the previous entry, the it become the new low entry
                                          {
                                          min = next;
                                          }
                                }
                                       else
                                        {
                                             double average = (sum/count); //finds the average of all the entries
                                                         System.out.println("The highest number is " + max); // outputs the highest
                                               System.out.println("The lowest number is " + min); // outputs the lowest
                                               System.out.println("The average of all the numbers is " + average);  //outputs the average
                                                        
                                                  }
                                      }
                          }
                          
             inputStream.close( );
             }
           }
        • 1. Re: Reading numbers from a text file
          843785
          If you run this in a debugger, you'll see your problem.

          Basically, you've got 2 things to do:

          1. Read in data from a file
          2. Find the largest, smallest elements, and the average, and print that out

          You're having trouble because you're doing both at the same time. Do you know how to use ArrayList?
          • 2. Re: Reading numbers from a text file
            843785
            I've never used an Arraylist before. I'll look into.

            But I see what you're saying when I look at the code now though. I have it reading in the data, "while" at the same time doing the calculation and outputs.

            I'll try tinkering with it.

            Edited by: azreal04 on Jul 17, 2008 3:22 PM
            • 3. Re: Reading numbers from a text file
              843785
              I don't see the need to store the data in a list, but your code is messy. I would delete it and start over.
              • 4. Re: Reading numbers from a text file
                843785
                Well, I made an example program that will show a few things that might be useful to you. I didn't catch exceptions, I didn't ensure much of anything, but that stuff can be filled in. And my example may not be the best display of finesse, it works, and again it might show you a few things:
                import java.util.*;
                import java.io.*;
                
                public class FileNumber {
                
                     public static void main(String[] args) throws FileNotFoundException {
                          int high;
                          int low;
                          int count = 0;
                          int total = 0;
                          
                          Scanner input = new Scanner(System.in);
                          System.out.print("Enter file name: ");
                          Scanner file = new Scanner(new File(input.next()));
                          
                          if (file.hasNextInt()) {
                               int temp = file.nextInt();
                               high = temp;
                               low = temp;
                               count++;
                               total += temp;
                               
                               while (file.hasNextInt()) {
                                    int current = file.nextInt();
                                    count++;
                                    low = Math.min(current, low);
                                    high = Math.max(current, high);
                                    total += current;
                               }
                               System.out.println("Max of: " + high);
                               System.out.println("Min of: " + low);
                               System.out.println("Average of: " + ((double) total / count));
                          }     
                     }     
                }
                First, unless you ensure there are always positive and negative values, you can't assume a minimum or maximum.. What if the minimum was 9999? Or the max -9999? Using Math.min and Math.max based on the first piece of input read solved this problem.

                Another thing is that avoiding too many nested loops can be a good thing, they get complicated fast. Anyway, there are lots of things that could probably go wrong with my version, such as there being non-numbers in the file, but those are all issues not quite related to the topic :)

                Hope I helped

                Edit: Using an ArrayList is another option, if you look under the Java API here, you can add all the elements in the file to an ArrayList, and then look at them all in one pass (along with being able to know how many there are, which could avoid the fencepost issue I had to deal with).
                • 5. Re: Reading numbers from a text file
                  843785
                  I don't see the need to store the data in a list
                  There is no "need" for it. I suggest it only because then you can break the program down into 2 steps (a) loading the data, and (b) evaluating it. IMO breaking this problem into the 2 parts makes both parts more reusable.
                  • 6. Re: Reading numbers from a text file
                    843785
                    I don't see the need to store the data in a list, but your code is messy. I would delete it and start over. 
                    Well, I am sort of new at this. But I'll see if I can tighten it up.

                    Thanks everyone for the ideas and suggestions. You've been a great help.