Hallo Leute, ich habe ein Problem mit einem Array und .nextInt();
dies verursacht meine Ausgabezeile an der 3. Aufforderung zu verschieben, anstatt unter, und ernsthaft kann nicht herausfinden, was los ist.Java-Array und nextInt(); funktionieren nicht richtig
Ich habe versucht, .hasNextInt();
aber nichts, es gibt mir tatsächlich einen Fehler, so ist hier der 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;
}
}
Wie erwarten Sie, dass 'promptAndRead()' jemals endet? Es nennt sich bedingungslos rekursiv, also an welchem Punkt wird das aufhören? Ich meine, anders als der Eventual StackOverflowError oder eine InputMismatchException, wenn der Benutzer aufgibt und Müll eingibt. --- Das heißt, vorausgesetzt, der Benutzer gibt keinen 'a'-Wert von 1 ein. In diesem Fall wird Ihr Bildschirm mit Nachrichten * ad infinitum * überflutet. --- Nebenfrage: Wofür wird 'userInput1' verwendet? – Andreas
Warum haben Sie Ihre Frage als JavaScript-Tag markiert? –
Warum sind 'userInput' und' userInput1' int Arrays? Warum nicht einfache ganze Zahlen? – UnholySheep