Hi, If you look trough my code you can see that i have tried to print out some values (the mean value) with a scanner from a csv file with the help of an enhanced for loop (the absolut last loop) and it gives me NaN (not a number).
And i cannot figure out why as i get the values from the file through the loop and everyone says my code looks right. Can anyone help? Did we perhaps miss something?

package apelsinenn;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;


/**
 *
 * @author Patricia
 */
public class Apelsinenn implements Serializable {

    //instance variabler
    String fileName;
    ArrayList<Double> weight;


   //Konstruktor 
   //När man 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();
   }
  //metod för att läsa in filen måste ändra sökvägarna                  
   public void readFile(){

   Scanner input;

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


 while(input.hasNextDouble())  {                    

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

  } 
   //countAverage(weight); 

 }catch (FileNotFoundException e) {
 //System.out.println(e);


 for (int i = 0; i < weight.size(); i++) {

                  System.out.println( weight.get(i).toString());

                  } 

 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");

   }                
    /*
    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) { //kör en enhanced for loop passande för just arrayer
System.out.println(weight1);
}
System.out.println(this.fileName);

double sum =0;
double count = 0 ;
                           for(Double wg: weight){ 
                              sum += wg; 
                              count++;
                           }
                          System.out.println("Medelvärdet är   " + sum / count);


 }

}

Recommended Answers

All 49 Replies

NAN means, as you said "not a number". on which line do you get that error ? and what is the value you are trying to use as a numeral value ?

i get the error from this loop

public void printValue(){
for (Object weight1 : weight) { //kör en enhanced for loop passande för just arrayer
System.out.println(weight1);
}
System.out.println(this.fileName);
double sum =0;
double count = 0 ;
                           for(Double wg: weight){ 
                              sum += wg; 
                              count++;
                           }
                          System.out.println("Medelvärdet är   " + sum / count);

im getting the value from a csv file that i have written in previously into an arraylist .That csv file contains 200 different double values and im supposed with this loop to calculate the mean value.

NaN is most commony seen when you try to divide by zero, as may happen if the loop on line 8 above executes zero times, so line 12 is trying to print 0/0

so my issue here is that i have initialized a double sum = 0;
and double count = 0; ?

Shall i skip the 0? I understand what u told me but im little unsure of how to correct this

i take that back, i shouldnt remove the 0 but im so stuck now... if i write the actual numbers of sum and count i get my answer but im supposed to get this answwer from the loop so im soo frustrated right now

He is trying to say that your loop may not execute even once, in such case your print out will be printing out 0/0. Maybe print just count and see if it ever increases to begin with?

Post the file "orange.csv". What is the range of numbers that is acceptable?

Hm im getting 0.0 when i just print out count. I feel like my csv file doesnt even go in to the array. Feels like its empty but i do not know how that can be possible either.

The csv file orange contains the following values (200 of them):

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

well, try to print the array and see if it's empty

yeah i did that before and i get [] . DOes that mean its empty? Im guessing yes cus otherwise i would see the values right?

Yep
how do you read the file?

Yes, that looks like an empty array - which would explain the 0/0 == NaN

wow thats so weird since im adding the csv file to the arraylist and it tells me its added fine, but i guess at least we know the issue is somewhere else than the enhanced for loop.
Thanks for all your help :)

@Slavi

Im reading the csv file like this :

 public void readFile(){

   Scanner input;

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


 while(input.hasNextDouble())  {                    

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

  } 
   //countAverage(weight); 

 }catch (FileNotFoundException e) {
 //System.out.println(e);


 for (int i = 0; i < weight.size(); i++) {

                  System.out.println( weight.get(i).toString());

                  } 

 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");

   }                

Why are you printing the contents of weight only if the file is not found? If you can't find the file then weight will be empty!
Hint: Indenting your code properly isn't a luxury, or something you do only when the code is finished. It's an essential technique for getting your structure right in the forst place.

Your for loop is in the wrong place, it is inside the catch statement, move it after and try again

EDIT: Well, this is what james said as well but didn't see his reply as I had the thread opened b4 that :(

Oh, and I believe if you are running on windows machine, your path should be
// not \\

i did, unfortunately didnt change anything:

public void readFile(){

   Scanner input;

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


 while(input.hasNextDouble())  {                    

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

  } 
   //countAverage(weight); 

 }catch (FileNotFoundException e) {
 //System.out.println(e);

 }

 for (int i = 0; i < weight.size(); i++) {

                  System.out.println( weight.get(i).toString());



 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");

   }                

try
System.out.println(input.nextDouble());
right after the while loop

oh and change \\ to //

@JamesCherill

i cant find that problem you are refering to. Where am i printing the contents of weight only if its not found? :-/

It was inside the catch statement, you enter it if you get an exception, but you moved it out ...
did you change \\ with // in your path ...?

oh i see.

well in our instructions the teacher has an example such as (".\src\filejava\outliers.csv");

so i dont think its anything wrong with the \

i tried to change it thought but major errors, couldnt find the file

The latest version is worse! You now have an empty catch block, so you will never know if the file was found or not. Alwyas use an e.printStackTrace(); until/unless you know it's right to do something else.
As for the slashes - you need a single slash in the path, regardless of windows vs linux. If its a back-slash you need to code that as a double back-slash because Java treats back-slash as an escape character in string literals. However, that's NOT true for a forward slash. Short version: replace \\ with /, not //

I just tried this, works like a charm for me

public class Test {
    static Scanner input;
    static ArrayList<Double> weight = new ArrayList<Double>();
    public static void main(String[] args){  
        try { 
          input  =  new Scanner(new FileInputStream ("C://Users//Slavi//workspace//Tests//src//DeleteMe//file.txt"));                                           
          while(input.hasNextDouble())  {                                                  
              weight.add(input.nextDouble());
          } 
         }catch (FileNotFoundException e) {
             e.printStackTrace();
         }
        for (int i = 0; i < weight.size(); i++) {
             System.out.println( weight.get(i).toString());
        } 
    }
}

the output was

2.2
3.3
4.4

That's interesting. I wouldn't expect that to work! Can you try it with single slashes?

/ and // worked no problem

I dont know if you missunderstand what i want to do with my programme.
In that section we are discussing im not supposed to print it out to the console, its supposed to print in or add (my english sucks) the csv file into an arraylist.

In the later section though, the last enhanced for loop is supposed to print out the mean value from the csv file. So im not supposed to print out the values of the csv file under the readfile() method in the output window

/ and // worked no problem

Hmmm... I tried creating a File with // in the path, then printing its canonicalPath, and found the // to have been replaced by single / characters.
Looks like the File constructor is doing some extra parsing and correcting of file names.

The print that we are doing there is just to check whether values were read from the file and added to the arraylist ...

fix your catch statement as this:

catch (FileNotFoundException e) {
             e.printStackTrace();
         }

and then this ..

 while(input.hasNextDouble())  {
              double value = input.nextDouble();
              System.out.println("Inside while with a value of "+ value);
              weight.add(value);
          } 

so that we can see whether your file is being read or not ...
not sure why it would give you an error if the file path is with /

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.