2014-09-28 100 views
0

我似乎遇到此代碼的問題。目的是找出在5面模具上擲出1的平均嘗試次數。我想我有數學權利;我只是不能讓while循環讀取文本文件的工作。閱讀文本文件時遇到問題

import java.io.IOException; 
import java.io.PrintWriter; 
import java.io.File; 
import java.util.Random; 
import java.util.Scanner; 
public class BottleCapPrize 
{ 
    public static void main (String[] args) throws IOException 
    { 
     Random randy = new Random(); 

     PrintWriter outFile = new PrintWriter(new File("boost.txt")); 
     Scanner inFile = new Scanner(new File("boost.txt")); 

     Scanner in = new Scanner(System.in); 

     int trials; 
     int tries = 6; 
     int winCap = 6; 
     int token = 0; 
     double average; 
     int total = 0; 

     System.out.print("Please enter the number of trials: "); 
     trials = in.nextInt(); 

     for (int loop = 1; loop <= trials; loop++)  
     { 
      winCap = 6; 
      tries = 0; 
      while (winCap != 0) 
      { 
       tries++; 
       winCap = randy.nextInt(5); 
      } 
      outFile.println(tries); 
      System.out.println(tries); 
     } 

     while (inFile.hasNext()) 
     { 
      token = inFile.nextInt(); 
      total = total + token; 
     } 

     average = (double)total/(double)trials; 
     System.out.println("Average : " + average); 

     outFile.close(); 
     inFile.close(); 
     in.close(); 
    } 
} 
+0

什麼是你的電流輸出,什麼是您的文本文件的內容? – shinjw 2014-09-29 00:30:14

+0

你爲什麼要用同一個文件讀寫? – 2014-09-29 05:14:42

回答

0

我想你的意思

while (inFile.hasNextLine()) 

while (inFile.hasNextInt()) 

希望幫助!

0

您不關閉您的輸出文件。由於您的輸出文件也是您的輸入文件,因此除非先關閉輸出,否則將無法讀取輸入。

while (inFile.hasNext())之前移動outFile.close(),並且您已經關閉之前,不過outFile不要打開你的INFILE:

import java.io.IOException; 
import java.io.PrintWriter; 
import java.io.File; 
import java.util.Random; 
import java.util.Scanner; 
public class BottleCapPrize 
{ 
    public static void main (String[] args) throws IOException 
    { 
     Random randy = new Random(); 

     PrintWriter outFile = new PrintWriter(new File("boost.txt")); 

     Scanner in = new Scanner(System.in); 

     int trials; 
     int tries = 6; 
     int winCap = 6; 
     int token = 0; 
     double average; 
     int total = 0; 

     System.out.print("Please enter the number of trials: "); 
     trials = in.nextInt(); 

     for (int loop = 1; loop <= trials; loop++)  
     { 
      winCap = 6; 
      tries = 0; 
      while (winCap != 0) 
      { 
       tries++; 
       winCap = randy.nextInt(5); 
      } 
      outFile.println(tries); 
      System.out.println(tries); 
     } 

     outFile.close(); 
     Scanner inFile = new Scanner(new File("boost.txt")); 

     while (inFile.hasNext()) 
     { 
      token = inFile.nextInt(); 
      total = total + token; 
     } 

     average = (double)total/(double)trials; 
     System.out.println("Average : " + average); 

     inFile.close(); 
     in.close(); 
    } 
}