I am getting this error and cannot figure out how to fix it. The class tutor couldn't figure it out. It is a poker program that deals out a hand, allows the user to replace up to 4 cards, and then analyzes it. It is designed to allow the user to play as many hands as they want, but the scanner whose input decides if they play or not isn't working and I can't figure out why.
Here is main code
import java.util.*;
public class Poker
{
public static void main(String[] args)
{
String game = "continue";
Run runpoker = new Run();
System.out.println("Enter 2 to play a hand or 1 to quit the game: ");
while (game == "continue")
{
game = ((Run)runpoker).playhand();//this is line 18
}
}
}
here is the method playhand that it is calling, that is the real main code
import java.util.Scanner;
public class Run
{
public String playhand()
{
int r = 1;
int limit = 0;
// create a new, shuffled Deck
Deck d = new Deck();
Hand h = d.deal();
h.sort();
System.out.println(h);
System.out.println("Which cards would you like to replace, up to 4");
System.out.println("Enter 0 when finished");
Scanner in = new Scanner(System.in);
r = in.nextInt();
while (r > 0 && r < 6 && limit < 4)
{
if (r > 0)
h.replace(d, r - 1);
limit++;
r = in.nextInt();
}
h.sort();
System.out.println(h);
String result = h.analyze();
System.out.println(result);
String answer;
System.out.println("Would you like to play again? Enter 'continue' to play again or 'quit' to stop playing: ");
in.close();
Scanner input = new Scanner(System.in);
answer = input.nextLine();//this is line 34
input.close();
return answer;
}
}
There are other classes but they shouldn't affect the scanner. Here is the error
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Run.playhand(Run.java:34)
at Poker.main(Poker.java:18)
The intial Carriage return pressed after
System.out.println("Enter 2 to play a hand or 1 to quit the game: ");
while ((game = scan.nextInt()) == 2)
is never consumed and is still on the input when playHand
is called.
So before calling playHand
call scan.nextLine();