2014-09-28 72 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(); 
    } 
}