質問

コイン投げの「勝ち」か「負け」を生成するプログラムを作ろうとしていますが、 出力 データをファイルに保存し、そのデータを読み取って計算します。 平均, 、しかし、私は'を取得しています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 ライン全体が「win!」であるかどうかを確認してください。そして、「勝つ!」だけ .contains ラインが「勝ち」があるかどうかを確認するためにチェックします。初期化。)

他のヒント

テストするリーディングループ内で inFile.hasNextLine(), 、ただし、次のトークンを取得しようとします。 inFile.next(). 。ただし、次の行があるからといって、次のトークンがあるとは限りません。

どちらか変更 hasNextLine()hasNext(), 、または変更します next()nextLine() (すべてのトークンが別の行にある場合)。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top