0

我在试图读入数组的文件中的一行中有一个空格分隔的 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)
4

2 回答 2

7

st.countTokens()给出剩余的数字标记。当您有 18 个令牌时,还剩下 18 个令牌,所以您停止。我建议您不要这样做,而是阅读建议以下模式的文档

 StringTokenizer st = new StringTokenizer("this is a test");
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }
于 2013-09-02T20:40:36.517 回答
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();
   }
于 2013-09-02T20:52:58.797 回答