2014-09-28 5 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

+0

왜 같은 파일을 읽고 쓰고 있습니까? –

답변

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(); 
    } 
} 
관련 문제