Pergunta

Estou tentando fazer um programa que gere 'vitória' ou 'perda' no lançamento de uma moeda, saída os dados em um arquivo e leia esses dados para calcular o média, mas estou recebendo um 'java.util.NoSuchElementException' erro.Não sei bem por que estou recebendo isso.Ajuda seria muito apreciada.

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);

        }
    }
Foi útil?

Solução

mudar inFile.next() para inFile.nextLine()

além disso, você vai querer mudar if (token.equalsIgnoreCase( "WIN!" )) para if(token.contains("WIN!")) caso contrário, nunca passará (.equals Verifique se a linha inteira é "Win!" e apenas "vence!", .contains Verifica para ver se a linha tem "Win!" iniciar.)

Outras dicas

No loop de leitura você testa inFile.hasNextLine(), mas tente obter o próximo token inFile.next().No entanto, ter uma próxima linha não significa necessariamente que exista um próximo token.

Qualquer mudança hasNextLine() para hasNext(), ou alterar next() para nextLine() (desde que todos os tokens estejam em linhas separadas).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top