-1

到目前为止我所拥有的:

import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;

public class FileEg
{
  public static void main (String [] args) throws Exception
  { int sum = 0, ctr = 0;
    double next;
    String line;
    String filename = "eg.txt";
    StringTokenizer st;
    PrintWriter outFile = new PrintWriter("eg.out");
    outFile.println("Output File");
    try
    { Scanner inFile = new Scanner(new FileReader (filename));
      while (inFile.hasNext())
      { line = inFile.nextLine();
        st = new StringTokenizer(line);
        while (st.hasMoreTokens())
        { next = Double.parseDouble(st.nextToken());
          sum += next;
          ctr++;
          outFile.println(next);          
        }
    }     
    outFile.println("number of integers read is " + ctr);
    outFile.println("average is " + sum/(double)ctr);
    outFile.close();
    }     //end of try
   catch(FileNotFoundException e)
   { System.out.println ("The file eg.dat was not found.");
   }
   catch(NumberFormatException e)
   { System.out.println ("sorry - number format error");
     System.out.println(e);
   }
  }
}

我需要得到至少 2 行不同的输出,并且一行上的数字超过一个。到目前为止,它在输出文件中是这样出现的。

输出文件

2.5

6.2

9.3

1.2

3.5

6.1

5.0

8.0

4.0

8.0

读取的整数数为 10 平均为 5.2

4

1 回答 1

0

请原谅答案列表,因为我还不能发表评论。但我认为 JB Nizet 试图让你做的是这样的事情(我还没有测试过这个提醒你,但它应该很接近):

int numbCounter = 0;  
while (inFile.hasNext())     
  { line = inFile.nextLine();
    st = new StringTokenizer(line);
    while (st.hasMoreTokens())
    { next = Double.parseDouble(st.nextToken());
      sum += next;
      ctr++;
      if (numbCounter <5){
      outFile.print(next + " ");
      }
      else if(numbCounter == 5){
          outFile.println();
          outFile.print(next + " ");
      }
      else {
          outFile.print(next + " ");
      }

      numbCounter++;
    }
  }
于 2013-02-21T02:05:08.997 回答