为什么我的Java程序只在文件中添加了一半的数字列表?

时间:2013-09-02 20:32:00

标签: java arrays

我在文件中的一行中有36个数字的空格分隔列表,我试图将其读入数组。我的程序读取整行,但只添加了18个数字。有谁看到原因?

谢谢。

    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)

2 个答案:

答案 0 :(得分:7)

st.countTokens()给出了数字代币。当你有18个令牌时,剩下18个令牌让你停下来。而不是这样做,我建议你阅读建议以下模式的文档

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

答案 1 :(得分:1)

我建议使用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();
   }