Hi guys,

After 10 days of googling and trying I finally must ask. This is not an assignment for school but its a practise one for the upcoming assignment in a few weeks.

So i have the weights of 200 oranges in a csv file. With this csv file i was supposed to create an array, serialize the object Apelsinn in to orange.ser and then deserialize it. All this is done without any trouble but next step is for the user through the interface be able to see the mean weight of the 200 oranges in the csv file.

I have already opened this csv file myself and calculated the weight of all the 200 oranges which was all together 14216,21
and i took that amount and divided it by 200 as you do for the mean weight and got 71,08155.

Anyhow, what i dont get, is how to calculate this from the csv file. I hardly believe that what they want us to do is to simply create two variables such as double mean; and double amount = 200; double weights = 14216,21 and then :

mean = weights/amount;

and then use a scanner or messagedialog with joptionpane and print it out to the consol.
I doubt it is just that easy but then again i so please guys give me a hint cus that is the next step at the end of my code. So here is my code so far.

 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package apelsinenn;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.util.Scanner;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;



/**
 *
 * @author Pati
 */
public class Apelsinenn implements Serializable {
    //instance variabler
    String fileName;
    ArrayList weight;


   //Konstruktor 
   //När du skapar ett objekt med NEW så kallas denna konstruktor.
   public Apelsinenn(){

   fileName = "orange";   
   weight = new ArrayList();

   }



    //Main metoden som gör alla anrop
   public static void main(String[] args) throws IOException {

                    Apelsinenn apelsin = new Apelsinenn();

                   apelsin.readFile(); apelsin.printObject();
                  apelsin.readObject();
   }


   public void readFile(){

                Scanner input;

                  try { 
                         input  =  new Scanner(new FileInputStream ("C:\\javamapp\\orange.csv"));                                           

                         //while((line = input.readLine()) !=null) {  
                           while(input.hasNextDouble())  {                    

                           double vikt = input.nextDouble();                                  
                           weight.add(vikt);

                           }  
                       }catch (IOException e) {
                     //System.out.println(e);
                     System.out.println("Någonting gick fel, det gick inte att Läsa från filen");
                 }
                  System.out.println("Filen har läst in till ArrayList weigth");



                  for (int i = 0; i < weight.size(); i++) {
                  System.out.println( weight.get(i).toString());
                  }          

   }               

   /*
    En metod för att skapa ett Apelsin Objekt ock skriva det till fil.
   */
   public void printObject(){

       //Apelsinenn apelsin = new Apelsinenn();

        try {
            ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("C:\\javamapp\\orangeWeights.ser"));
            output.writeObject(this);
            output.close();

        } catch (IOException ex) {
           System.out.println("Något gick fel med att skriva objektet till filen");
        } 
        System.out.println("Objektet har skrivits i orangeWeights.ser");

 }

    /*
     Metod för att Deserializable objektet och läsa det från filen som vi skapa i printOject metoden
   */
public void readObject(){

        try {
            ObjectInputStream input = new ObjectInputStream(new FileInputStream("C:\\javamapp\\orangeWeights.ser"));
            Apelsinenn nyapelsin = (Apelsinenn)input.readObject();
            nyapelsin.printValue();
            //System.out.println(nyapelsin.toString());  //skriver ut objektadressen i minnet

        } catch (IOException ex) {
          System.out.println("Fel vid försök att läsa från filen");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Apelsinenn.class.getName()).log(Level.SEVERE, null, ex);
        }

}        
        public void printValue(){

        for (Object weight1 : weight) {
            System.out.println(weight1);
        }
        System.out.println(this.fileName);


        }
}

any help is appriciated. thanks

Anyhow, what i dont get, is how to calculate this from the csv file. I hardly believe that what they want us to do is to simply create two variables...

It sounds like it really is that simple. I read "calculate from the CSV file" to mean that you should use the data from the files, i.e., count apples and sum weights as you read the file, and divide after you're done loading. Perhaps the focus of the assignment is to be able to calculate the mean for whatever data are provided?

hi, thanks for replying. Seems like im supposed to initialize a counter and count how many delimiters that are used in the csv file.
Then sum up the content for every time the scanner finds a delimiter in a total variable and then divide the total amount of delimiters (i suppose) with the sum of the counter. I just really feel confused on how to do it. i tried to implement it under the readfile() method but nothing happened

I highly doubt that you need to access the file again, unless you are given a new file to do so. Anyway, there are 2 possible translation from the requirement.

1) The method simply asks to return the mean value. In this case, the method does not have any argument and it is an instance method (i.e. getMeanValue()). Therefore, your class instance should have stored the data in itself already. Simply return the value by dividing the sum with total number count.
2) The method asks for the return mean value and give a csv file path & name (i.e. getMeanValue(String fullPathName) or getMeanValue(String fullPaht, String fileName)). In this case, the method should be static and you will have to access the given file in order to calculate the mean value.

Therefore, which one is it supposed to be?

i think the second option is the correct one. I just dont know why i feel so lost and unsure of the syntax, where is should apply this method inside my code. ill try and see..

Seems like im supposed to initialize a counter and count how many delimiters that are used in the csv file.

There's one orange per row, right? We want to count oranges, so count rows, not delimiters.

You're currently using delimiters:

while(input.hasNextDouble())

...which may work for this simple example, but it's not correct and it will likely cause you problems if you try this elsewhere.

You had the right idea, but commented it out:

while((line = input.readLine()) !=null)

Each line in the input is a row. This will get you one row each time through the loop; easy to count.

Then focus on getting vikt out of line.

Then sum up the content ... in a total variable and then divide the total ... with the sum of the counter

You're already summing the weights:

weight.add(vikt)

...so all that should be left is to divide at the end.

thank you! i really suck at java but im so eager to learn!! Im sure this will solve my issue :)

but i want to point out that the csv file contents the weights of 200 oranges so is it really right to count rows? The orange file looks like this:

62.91
57.29
55.32
60.62
62.35
66.33
63.38
54.57
74.22
64.88
59.09
55.41
52.95
66.05
62.19
60.38
66.47
58.13
50.03
55.01
62.83
45.71
52.61
64.99
58.44
51.17
63.42
67.44
64.18
65.01
68.01
43.46
52.12
36.94
45.32
56.01
56.77
57.17
68.95
59.67
55.8
73.29
62.86
56.89
45.82
59.25
65.2
57.84
58.88
61.54
63.21
57.91
59.66
52.17
47.03
48.98
56.12
68.3
58.39
69.77
65.91
63.67
55.8
62.3
63.34
64.46
62.6
69.77
64.17
55.94
95.42
91.99
98.17
98.84
95.04
99.68
96.59
99.61
90.99
88.14
92.01
92.59
90.57
95.06
91.73
74.86
55.76
92.77
66.62
70.4
87.29
86.97
77.83
90.78
73.25
73.62
70.05
83.76
81.2
85.94
92.73
77.26
96.22
86.79
86.87
85.27
83.26
79.24
79.81
73.57
88
56.98
85.71
72.15
71.53
78.89
85.11
64.37
64.04
98.54
64.75
83.94
79.54
88.49
84.41
87.2
75.92
71.98
84.51
82.27
87.99
66.28
79.02
74.19
84.05
92.41
82.4
74.63
94.15
84.55
69.55
79.97
87.03
89.62
89.19
89.47
67.79
74.36
78.51
77.84
72.09
72.94
105.49
35.99
54.92
76.31
77.14
62.71
70.61
39.44
51.38
71.46
67.73
68.57
76.98
81.67
77.79
90.02
67.08
63.5
88.26
62.65
48.17
55.92
62.54
54.4
67.84
43.43
74.33
101.3
68.15
98.92
63.17
52.27
65.84
86.06
40.35
73.73
86.88
101.12
78.42
61.13
59.74
97.93
73.18
62.11
74.81
70.1
71.54
68.79

You simply count if and only if you could parse the weight (nextDouble()). If you can't add the weight, don't count. The reason is to prevent an empty line mixed inside the file. Also, to ensure that you are correctly counting.

the csv file contents the weights of 200 oranges so is it really right to count rows?

Well, it's not wrong... but it's also true that this example is simple enough that you can just read numbers until you're done, so that's not really wrong either.

This exercise isn't really about CSV data, though you could interpret it as a single-column table. I'm talking about rows because that's a concept that will be useful for a wider variety of data.

For example, say there were more bits of information about the oranges... maybe diameter and hue. Then you might have a data file that looks like this:

74.81,6.43,30
70.1,6.22,31
71.54,6.11,28
68.79,5.98,33

...and you'd have to separate fields at the commas to get the weight.

All of this is just to say that if you think of each line in the data file as a row in a table, it will help you understand more complicated scenarios when you get to them.

Thank you Guasano! And all of you guys. I managed to solve it :)
I added a an enhanced for loop to my code.

double sum =0;
double count = 0 ;

    for(Double a: weight){
    sum += a; 
    count++;
   }

 System.out.println("Medelvärdet är   " + sum / count);

i appreciate you help. thanks a lot

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.