简体   繁体   中英

Why does my Java program add only half a list of numbers in a file?

I have a space delimited list of 36 numbers in a single line in a file that I am trying to read into an array. My program reads the entire line, but adds only 18 of the numbers. Does anyone see the reason?

Thank you.

    StringTokenizer st;

    try{
       BufferedReader br = new BufferedReader(
                 new FileReader("Scores.txt"));


       String line = br.readLine();
       double avg = 0.0;
       double sum = 0.0;
       int count = 0;


       while (line!=null)
        {
               st = new StringTokenizer(line);
                    System.out.println("Total tokens : " + st.countTokens());
               for(int i = 0; i < st.countTokens(); i++)
                {
                       avg += Double.parseDouble(st.nextToken());
                       count++;
                       System.out.println("i: " + i); 
                }
            System.out.println(line);

            line = br.readLine();
       }

       br.close();
       sum = avg; 
       System.out.println("Sum: " + sum); 
       System.out.println("Count: " + count);
       avg = avg/count;
       System.out.println("Avg: " + avg);



    }catch(Exception e)

st.countTokens() gives the number tokens left. When you have 18 tokens, there are 18 tokens left so you stop. Instead of doing this I suggest you read the documentation which suggest the following pattern

 StringTokenizer st = new StringTokenizer("this is a test");
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }

I suggest using String.split() :

    String[] lineNum;
    int n;
    while (line!=null)
    {
           lineNum = line.split(" ");
           n = lineNum.length;
           System.out.println("Total numbers : " + n);
           for(int i = 0; i < n; i++)
            {
                   avg += Double.parseDouble(lineNum[i]);
                   System.out.println("i: " + i); 
            }
            count += n;
            System.out.println(line);
            line = br.readLine();
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM