dimanche 18 septembre 2016

Java array and nextInt(); do not work properly

Hello guys I am having a problem with an array and a .nextInt(); this is causing my output line at the 3rd prompt to shift up instead of under, and seriously cannot figure out what's wrong.

I have tried .hasNextInt(); but nothing, it actually gives me an error, so here is the code:

import java.util.Random;
import java.util.Scanner;

public class birthday {

    public static void main(String[] args) {
        System.out.println("Welcome to the birthday problem Simulator\n");
        String userAnswer="";
        Scanner stdIn = new Scanner(System.in);
        do {
            int [] userInput = promptAndRead(stdIn); //my problem
            double probability = compute(userInput[0], userInput[1]);

            // Print results
            System.out.println("For a group of " + userInput[1] + " people, the probability");
            System.out.print("that two people have the same birthday is\n");
            System.out.println(probability);

            System.out.print("\nDo you want to run another set of simulations(y/n)? :");

            //eat or skip empty line
            stdIn.nextLine();
            userAnswer = stdIn.nextLine();


        } while (userAnswer.equals("y"));

        System.out.println("Goodbye!");
        stdIn.close();
    }

    // User input prompt where you make the simulation. For people and return them as an array
    public static int[] promptAndRead(Scanner stdIn)
    {
        System.out.println("Please enter the number of simulations you want to do: ");
        int[] userInput =new int [2]; //my problem
        userInput[0]= stdIn.nextInt(); //my problem
        System.out.println("Please enter the size of the group you want : ");
        int[] userInput1 = new int [2];
        userInput[1] = stdIn.nextInt();
        int a = userInput[1];
        while (a<2 || a>365)
        {
            System.out.println("please type the number that is between 2~365");
        }


        System.out.println();

        return promptAndRead(stdIn);

    }


    // Method for calculations
    public static double compute(int numOfSimulation, int numOfPeople)
    {
        for (int i =0; i < numOfPeople; i++)
        {
        Random rnd = new Random(1);
        //Generates a random number between 0 and 364 exclusive
        int num = rnd.nextInt(364);
        System.out.println(num);
        System.out.println(num / 365 * numOfPeople * numOfSimulation);
        }
        return numOfPeople;

    }
}




Aucun commentaire:

Enregistrer un commentaire