Link to home
Start Free TrialLog in
Avatar of awolarczuk
awolarczukFlag for Australia

asked on

how do i read a est file in to my array in java

hi all i know i am close but i cantseem to get over that final step to working this out, i am waiting to reading in a file to a array i have opened the file and created the array but just not to sure where to go next

my code is below

Thanks in advance
import java.io.*;
import java.util.Scanner;

public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read 

     int Count = 0; // this will set the Count to 0 

     while (input.hasNextLine()) // walking through the file a line at a time 
	 {
	     Count++; // counting the numbers in the file
	     input.nextLine();
	     System.out.println (Count);
	     
	 }
    
     input.close(); // closing the input from the file 
    
     if (Count < 1)
	 System.out.println ("The File " + fileName + " " + "needs to contain more then 1 number");
      else     
	  System.out.println (Count);
     return Count;
  }




    public static void readData(String fileName) throws IOException
  {
      Scanner input = new Scanner (new File(fileName));

     

      double [] num = new double [Count]; //create the array 

      

      for (int i = 0; i < numbers.length; i++)  // creating the array 
	  {
	      num = input.readLine();
	  }
         
  }

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

import java.io.*;
import java.util.Scanner;

public class Calculate
{
    public static int countData(String fileName) throws IOException
 {
ArrayList al = new ArrayList();
     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read

     int Count = 0; // this will set the Count to 0

     while (input.hasNextLine()) // walking through the file a line at a time
 {
     Count++; // counting the numbers in the file
 
 al.add ( input.nextLine());
     System.out.println (Count);
     
 }
   
     input.close(); // closing the input from the file
   
     if (Count < 1)
 System.out.println ("The File " + fileName + " " + "needs to contain more then 1 number");
      else    
  System.out.println (Count);
     return Count;
  }




    public static void readData(String fileName) throws IOException
  {
      Scanner input = new Scanner (new File(fileName));

     

      double [] num = new double [Count]; //create the array

     

      for (int i = 0; i < numbers.length; i++)  // creating the array
  {
      num = Double.parseDouble(input.readLine());
  }
         
  }
You need to parse the lines which you read in the second method into double
Avatar of awolarczuk

ASKER

thanks mate, so much this looks great but i need to do it with an array not a arraylist could you please help me with that
I showed how to do it using Double class static method
Please, check if the name of method of the scanner for readling next line is readLine()
import java.io.*;
import java.util.Scanner;

public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read

     int Count = 0; // this will set the Count to 0

     while (input.hasNextLine()) // walking through the file a line at a time
       {
           Count++; // counting the numbers in the file
           input.nextLine();
           System.out.println (Count);
          
       }
   
     input.close(); // closing the input from the file
   
     if (Count < 1)
       System.out.println ("The File " + fileName + " " + "needs to contain more then 1 number");
      else    
        System.out.println (Count);
     return Count;

     readData(Count);
  }




    public static void readData(String fileName ) throws IOException
  {
      Double Count;
      Scanner input = new Scanner (new File(fileName));

     

      double [] num = new double [Count]; //create the array

     

  }
You don't need arraylist - discard that my change in the first method. Look only at the change in the second method
this is the code i was working with but i do need to use the array not a array list sorry i am still new to JAva :( i tried to pass the count to the other method
I added arraylist just to show you that with arraylist you don't need to read it twice.
Discard these my changes in the first method.
Look at the parsing part in the second methoid - it is important - you cannot assign string to double
yea cool mate i do understand that but at this stage i need to just use no list (this is for study if it was for me i would with no issues use it ) i am still learning :)
To pass count from one method to another you actually can add one more int parameter and call second method from the first
cool cool i used ur code for the 2nd meth and i am getting this error
i know what you mean and i know what i am doing wrong but i am just not how to correct it
i have tried to do a Double Count; but i get the same issuesw


C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>JAVAC CalculateTest.java
.\Calculate.java:35: readData(java.lang.String) in Calculate cannot be applied to (int)
     readData(Count);
     ^
.\Calculate.java:48: incompatible types
found   : java.lang.Double
required: int
      double [] num = new double [Count]; //create the array
                                  ^
2 errors

C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>
ok so how would i do that
You don't need any list - keep the first method exactly as yoiu had, only in the end of it add call to the second method
readData(fileName, count);
And in declaration of second method add int count as parameter:
public static void readData(String fileName,int count)
This is the full code i have and i am still getting

C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>JAVAC CalculateTest.java
.\Calculate.java:35: readData(java.lang.String,java.lang.Double) in Calculate cannot be applied to (java.lang.String,int)
     readData(fileName,Count);
     ^
.\Calculate.java:48: incompatible types
found   : java.lang.Double
required: int
      double [] num = new double [Count]; //create the array
                                  ^
2 errors

C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>

QHt dumb thing am i doing wrong mate
import java.io.*;
import java.util.Scanner;

public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read 

     int Count = 0; // this will set the Count to 0 

     while (input.hasNextLine()) // walking through the file a line at a time 
	 {
	     Count++; // counting the numbers in the file
	     input.nextLine();
	     System.out.println (Count);
	     
	 }
    
     input.close(); // closing the input from the file 
    
     if (Count < 1)
	 System.out.println ("The File " + fileName + " " + "needs to contain more then 1 number");
      else     
	  System.out.println (Count);
     return Count;

     readData(fileName,Count);
  }




    public static void readData(String fileName, Double Count ) throws IOException
  {
      
      Scanner input = new Scanner (new File(fileName));

     

      double [] num = new double [Count]; //create the array 

      

  }

Open in new window

import java.io.*;
import java.util.Scanner;

public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read

     int Count = 0; // this will set the Count to 0

     while (input.hasNextLine()) // walking through the file a line at a time
 {
     Count++; // counting the numbers in the file
     input.nextLine();
     System.out.println (Count);
     
 }
   
     input.close(); // closing the input from the file
   
     if (Count < 1)
 System.out.println ("The File " + fileName + " " + "needs to contain more then 1 number");
      else    
  System.out.println (Count);
readData(fileName, Count);
     return Count;
  }




    public static void readData(String fileName , int Count) throws IOException
  {
      Scanner input = new Scanner (new File(fileName));

     

      double [] num = new double [Count]; //create the array

     

      for (int i = 0; i < numbers.length; i++)  // creating the array
  {
      num = Double.parseDouble(input.nextLine());
  }
         
  }
Count is int and should be declared as int in the definition of the second method
ok ok i worked it out sorry mate, but i am now back to the first question how do i read the text file in to my array not a array list
But we have no arraylist now - look at the code I posted second time. No arraylist - all we do is reading to your array num
but now i am getting some weird errors

tha code is still like is showed u


C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>JAVAC CalculateTest.java
.\Calculate.java:36: unreachable statement
     readData(fileName,Count);
     ^
.\Calculate.java:38: missing return statement
  }
  ^
2 errors

C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>
Only the file should have numbers only - one number per line - and nothing else on the line
sorry i missed that :)
matie i think we are alomost there i am now only getting theses errors


C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>JAVAC CalculateTest.java
.\Calculate.java:52: cannot find symbol
symbol  : variable numbers
location: class Calculate
      for (int i = 0; i <numbers.length; i++)
                         ^
.\Calculate.java:55: incompatible types
found   : double
required: double[]
              num = Double.parseDouble(input.nextLine());
                                      ^
2 errors

C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>
In order to execute it you'll need to add the main method:

public static void main (String [] args) {
try{
countData("filename.txt");
}catch(Exception ex){
System.out.println(ex.toString();
}}

i already have this and forthe most part it works apart from the errors i am getting i just showed you


import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.IOException;

public class CalculateTest
{
   public static void main(String[] args)
   {
 
       String  filename; // This will store the value for the keyboard input
       Calculate account; // This will allow the connectiong to the Calculate file

       // This will create the scanner object for the keyboard input
       Scanner Keyboard = new Scanner (System.in);

       // This will Create the Calculate object
       account = new Calculate();

       //This will formate the output for the user to read to 4 Decimal places
       DecimalFormat formatter = new DecimalFormat ("#0.0000");


       System.out.print ("Enter the name of the data file: ");
       filename = Keyboard.nextLine();

       try
         {
       Calculate.countData(filename); //passing the file name that has been given bu the user to the Calulate file
       }
       catch (IOException e)
         {
             e.printStackTrace();
         }

       //System.out.println (Count);

   }
}
Yes, the array everywhere should be num, not numbers

In the assignment and parsing line it should come with index
num[I] = Double.parse...

And I shoiuld be lowere case
thanks mate now i am down to tow last errors


C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>JAVAC CalculateTest.java
.\Calculate.java:36: unreachable statement
     readData(fileName,Count);
     ^
.\Calculate.java:38: missing return statement
  }
  ^
2 errors

C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>

o cant work out why i have both of them here
Maybe addData line is after return ?
Should be before return
sorry amte it is getting late here waht is addData??
its ok i worked it out

mate you have been so great my next step is to go through the array and add up all the number but i will work that out :) thanks mate, well unless you want to give me a hint :)
Sure before starting reading
Say

double sum = 0.0;

And then after parsing line
Say

sum += num[I];

In the end sum will contain your sum
cool matethank so much one lst thing i have a issue with is when i count atthe top the number for items in the file i am getting three im a empty doc for some reason can u please help me here
Don't understand what you mean
when you are counting number of lines in the file you are getting what?
you are getting three in an empty file?
maybe there are three empty lines - just returns?
Your file should have one number on each line and should not have
empty lines.

Ok, I don't hear from you, I'll be driving now.
when i read in a file that does not have any thing in it i should get a count of 0 and for some reason i am getting a count of three,
when i do a file with 20 line it is comming up iwth no issues


also i have just done what you suggested before with a little difference and getting a issue i will show you, mate you have been great thank for keeping on helping me and expaing as you re going, are you sure you are not a teacher :)

the counting issue is in the top methord and the issue i am currently having with adding up is in the very last one, i thought i was doing well there for a moment L:)


import java.io.*;
import java.util.Scanner;

public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read 

     int Count = 0; // this will set the Count to 0 

     while (input.hasNextLine()) // walking through the file a line at a time 
	 {
	     Count++; // counting the numbers in the file
	     input.nextLine();
	     System.out.println (Count);
	     
	 }
    
     input.close(); // closing the input from the file 
    
     if (Count < 1)
	 System.out.println ("The File " + fileName + " " + "needs to contain more then 1 number");

      else     

	  System.out.println (Count);
      readData(fileName,Count);
      return Count;
    
     
  }




    public static int readData(String fileName, int Count ) throws IOException
  {
      
      Scanner input = new Scanner (new File(fileName));

     

      double [] num = new double [Count]; //create the array 

      for (int i = 0; i <num.length; i++)

	  {
	      num[i] = Double.parseDouble(input.nextLine());  // this will fill in the array 
	  }
      calMean(num);  //passing the array to the calMean 
      return 1;
      

  }

  public static double calMean(double num[])
  {
      Double sum = 0.0;

      for (int i = 0; i <num.length; i++)
	  {
	      num[i] = Double.parseDouble(num.nextLine());
	      sum += num[i];
	  }

    
      System.out.println (sum);
      return 1;

Open in new window



This is the code:
import java.io.*;
import java.util.Scanner;

public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read

     int Count = 0; // this will set the Count to 0

     while (input.hasNextLine()) // walking through the file a line at a time
	 {
	     Count++; // counting the numbers in the file
	      input.nextLine();
	    // System.out.println (Count);

	 }

     input.close(); // closing the input from the file

     if (Count < 1)
	 System.out.println ("The File " + fileName + " " + "needs to contain more then 1 number");

      else

	  System.out.println (Count);
      readData(fileName,Count);
      return Count;


  }




    public static void readData(String fileName, int Count ) throws IOException
  {

      Scanner input = new Scanner (new File(fileName));



      double [] num = new double [Count]; //create the array

      for (int i = 0; i <num.length; i++)

	  {
	      num[i] = Double.parseDouble(input.nextLine());  // this will fill in the array
	  }
   double avgnum =    calMean(num);  //passing the array to the calMean

       System.out.println("average: " + avgnum);

  }

  public static double calMean(double num[])
  {
      Double sum = 0.0;

      for (int i = 0; i <num.length; i++)
	  {
	      //num[i] = Double.parseDouble(num.nextLine());
	      sum += num[i];
	  }


      System.out.println (sum);

      return sum/num.length;
  }
    public static void main(String [] args){
        try{
        countData("fileNumbers.txt");
        }catch(Exception ex){
            System.out.println(ex.toString());
            ex.printStackTrace();
        }
    }

}

Open in new window


This is the run against empty file:

The File fileNumbers.txt needs to contain more then 1 number
0.0
average: NaN

Open in new window


This is the run against the file having three
numbers
3.0
4.0
5.0

Output:

3
12.0
average: 4.0

Open in new window


neither of these files can have empty lines, even
a single empty line in the end will break it

Ok, now I'm really leaving;
look at this code in the meantime

mate thanks so much i am gettings it to work the only issue i am still having with the the count i am now getting this issue when i ask it to read a file with no data, the code is below


C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>JAVA CalculateTest
Enter the name of the data file: none.data
Exception in thread "main" java.lang.NumberFormatException: empty String
        at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:994)
        at java.lang.Double.parseDouble(Double.java:510)
        at Calculate.readData(Calculate.java:59)
        at Calculate.countData(Calculate.java:38)
        at CalculateTest.main(CalculateTest.java:38)

C:\Users\awolarczuk\Desktop\Working Stuff\UNE\Computer Science\assignments\Computer Science\Assignment P4>
public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read 

     int Count = 0; // this will set the Count to 0 

     while (input.hasNextLine()) // walking through the file a line at a time 
	 {
	     Count++; // counting the numbers in the file
	     input.nextLine();
	     
	     
	 }
    
     input.close(); // closing the input from the file 
    
     if (Count < 1)
	 
	 return Count;
     

      else     

	 
      readData(fileName,Count);
      return Count;
    
     
  }



/* Assignment_P4 reads a set of real numbers from a file and   
 * stores them in an array of type double.
 *
 * The program then calculates and displays the mean, variance, and 
 * standard deviation of these real numbers.
 *
 * Input:   a set of real numbers
 * Output:  mean, variance, standard deviation
 *
 **********************************************************************/
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.IOException;

public class CalculateTest
{
   public static void main(String[] args)
   {
  
       String  filename; // This will store the value for the keyboard input 
       Calculate account; // This will allow the connectiong to the Calculate file

       // This will create the scanner object for the keyboard input
       Scanner Keyboard = new Scanner (System.in);

       // This will Create the Calculate object
       account = new Calculate();

       //This will formate the output for the user to read to 4 Decimal places 
       DecimalFormat formatter = new DecimalFormat ("#0.0000");


       System.out.print ("Enter the name of the data file: ");
       filename = Keyboard.nextLine();

       try
	   {
       Calculate.countData(filename); //passing the file name that has been given bu the user to the Calulate file 
       }
       catch (IOException ex)
	   {
	       System.out.println(ex.toString());
	       ex.printStackTrace();
	   }

       // System.out.println (Count);

   }
}

Open in new window

There was an empty line in this file - that's what says diagnostic

Look at my code - I tried empty file and it worked as you see in the output


matie i though i used you code sorry if i missed someting what did i miss
mate i have checked and recheck and cant find where i am going wrong here, sorry to be a pain mate

main code 


/* Assignment_P4 reads a set of real numbers from a file and   
 * stores them in an array of type double.
 *
 * The program then calculates and displays the mean, variance, and 
 * standard deviation of these real numbers.
 *
 * Input:   a set of real numbers
 * Output:  mean, variance, standard deviation
 *
 **********************************************************************/
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.IOException;

public class CalculateTest
{
   public static void main(String[] args)
   {
  
       String  filename; // This will store the value for the keyboard input 
       Calculate account; // This will allow the connectiong to the Calculate file

       // This will create the scanner object for the keyboard input
       Scanner Keyboard = new Scanner (System.in);

       // This will Create the Calculate object
       account = new Calculate();

       //This will formate the output for the user to read to 4 Decimal places 
       DecimalFormat formatter = new DecimalFormat ("#0.0000");


       System.out.print ("Enter the name of the data file: ");
       filename = Keyboard.nextLine();

       try
	   {
       Calculate.countData(filename); //passing the file name that has been given bu the user to the Calulate file 
       }
       catch (IOException ex)
	   {
	       System.out.println(ex.toString());
	       ex.printStackTrace();
	   }

       // System.out.println (Count);

   }
}


*******************************


/* Calculate contains methods that determines the number of data 
 * entries in a file, read the data into an array, and calculate 
 * and return the mean, variance of a set of numbers stored in an 
 * array
 *
 ***********************************************************************/
import java.io.*;
import java.util.Scanner;
import java.text.DecimalFormat;



public class Calculate
{
    public static int countData(String fileName) throws IOException
 {

     Scanner input = new Scanner (new File(fileName));  //this will allow the file to be opened and read 

     int Count = 0; // this will set the Count to 0 

     while (input.hasNextLine()) // walking through the file a line at a time 
	 {
	     Count++; // counting the numbers in the file
	     input.nextLine();
	     
	     
	 }
    
     input.close(); // closing the input from the file 
    
     if (Count < 1)
	 
	 return Count;
     

      else     

	 
      readData(fileName,Count);
      return Count;
    
     
  }




    public static int readData(String fileName, int Count ) throws IOException
  {
      
      Scanner input = new Scanner (new File(fileName));

     

      double [] num = new double [Count]; //create the array 

      for (int i = 0; i <num.length; i++)

	  {
	      num[i] = Double.parseDouble(input.nextLine());  // this will fill in the array 
	  }
      calMean(num, Count);  //passing the array to the calMean 
      return 1;
      

  }

    public static double calMean(double num[], int Count)
  {
      Double sum = 0.0;  //this will store the value for the part of the cal for to find out the means 
      Double mean; // this will store the value of the means 

      for (int i = 0; i <num.length; i++)
	  {
	      
	      sum += num[i];
	  }
      mean = (sum / Count);  // this will find out what the means is 

      calVariance (num,mean,Count);  // passing the mean and the array to the calVariance method
      
      
      return sum/num.length;      
  }

    public static double calVariance(double num[], double mean, int Count)
  {
      Double variance = 0.0;  //this will store the Variance
      Double std = 0.0;       //this will store the std value

      DecimalFormat formatter = new DecimalFormat ("#0.0000");

      for (int i = 0; i <num.length; i++)
	  {
	      variance += (1.0/Count * (Math.pow(num[i] - mean,2))); //working out the variance 

	  }
      std = Math.sqrt (variance); //working out and storing the std
     
      System.out.println ("\nMean is: " + (formatter.format (mean)));   //displaying the Mean to the user 
      System.out.println ( "Variance is: " + (formatter.format (variance))); //displaying th Variance to the user 
      System.out.println ("Std is: " + (formatter.format(std))); // displaying the std tot he user 
      return variance;      
  }


}

Open in new window

also attach the file you are using for testing - empty or not empty - it can be attched using File option
I'll come to my regular computer soon and I'll try it.
In the meantime please attach the file
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ONe of the best people that you can get to help you

Thanks mate