2013-02-20 84 views
-1

我有什麼至今:我如何在同一行輸出數字列表從一個文件中的java

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

+7

使用'print()'而不是'println ()'? – 2013-02-20 22:08:08

+0

@JB Nizet 但我需要更多,然後只有一行。加上然後「讀取的整數數量是10 ...」與數字在同一行上。它需要像上面那樣,但至少有一行與多於一個數字。 – user2093182 2013-02-20 22:20:12

+0

@JB Nizet 或至少2行 – user2093182 2013-02-20 22:22:06

回答

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++; 
    } 
    } 
相關問題