문제

나는 동전 던지기에 대해 '승' 또는 '패'를 생성하는 프로그램을 만들려고 합니다. 산출 데이터를 파일로 저장하고 해당 데이터를 읽어서 평균, 하지만 '라는 메시지가 표시됩니다.java.util.NoSuchElementException' 오류.내가 이걸 왜 받는지 전혀 모르겠어..도움을 주시면 감사하겠습니다.

import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
    public static void main(String [] args) throws IOException
    {            
        int random;
        int loop = 1;
        double trials = 0;
        double winCounter = 0;
        double average;
        String token = "";

        //

        Scanner in = new Scanner(System.in);
        Random rand = new Random();
        PrintWriter outFile = new PrintWriter (new File("MonteCarloMethod.txt"));

        //User Input Trials
        System.out.print("Number of trials: ");
        trials = in.nextInt();

        //For loop (random, and print to file)
        average = 0;
        for(loop = 1; loop <= trials; loop++)
        {
            random = rand.nextInt(5);
            if(random == 1)
            {
                outFile.println("Trial: " + loop + " WIN!");
            }
            outFile.println("Trial: " + loop + " LOSE");
        }

        outFile.close();

        //read output 
        File fileName = new File("MonteCarloMethod.txt");
        Scanner inFile = new Scanner(fileName);
        while (inFile.hasNextLine())
        {
            token = inFile.next();
            if (token.equalsIgnoreCase( "WIN!" ))
            {
                winCounter++;
            }

        }

        //average and print average
        average = winCounter / trials * 100;
        outFile.println("Average number of caps to win: " + average);
        System.out.println("Average number of caps to win: " + average);

        }
    }
도움이 되었습니까?

해결책

변화 inFile.next() 에게 inFile.nextLine()

또한 당신은 변화를 원할 것입니다 if (token.equalsIgnoreCase( "WIN!" )) 에게 if(token.contains("WIN!")) 그렇지 않으면 결코 통과하지 못할 것입니다(.equals 전체 라인이 "승리"인지 확인하십시오. 그리고 "승리!", .contains 라인에 "승리"가 있는지 확인합니다. 그것에.)

다른 팁

읽기 루프에서 다음을 테스트합니다. inFile.hasNextLine(), 하지만 다음 토큰을 얻으려고 시도하십시오. inFile.next().그러나 다음 줄이 있다고 해서 반드시 다음 토큰이 있다는 의미는 아닙니다.

변경하거나 hasNextLine() 에게 hasNext(), 또는 변경 next() 에게 nextLine() (단, 모든 토큰이 별도의 줄에 있는 경우)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top