OrangePineapple OrangePineapple - 1 month ago 9
Java Question

program ends before reaching while loop

hi guys I'm trying to make a lottery program And I'm trying to get the users input to after asking if they want to retry playing. But my program ends before reaching the while loop.

public class Main {

public static void main(String[] args)
{

Scanner input = new Scanner(System.in);
String yn = "";

Lottery.getTicket();
Lottery.generateWinningNumbers();
System.out.print("\nWould you like to try again? ");

while(input.hasNextLine())
{
yn = input.nextLine();

if(yn.equalsIgnoreCase("y"))
{
Lottery.getTicket();
Lottery.generateWinningNumbers();
}
else
{
System.out.println("Done");
}

}
input.close();
}

}


edited: removed my codes for Lottery class. (Assignment for school)

Answer

You are using the Scanner Object

Scanner input = new Scanner(System.in);

in Lottery.getTicket and you do

input.close();

This means that System.in will be closed for the rest of the program

Try passing the Scanner object from main to other classes and method that need it.

Comments