如何从java中同一行的文件中输出数字列表

时间:2013-02-20 22:06:03

标签: java bluej

到目前为止我所拥有的:

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

1 个答案:

答案 0 :(得分: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++;
    }
  }