Java: User Input - Scanner - Program Hangs After Second Input - java

I'm making a console-based game of black jack that prompts the user asking him/her if he/she wants to: 'h' for hit, 's' for stay, or 'q' for quit. I'm using the Scanner class to receive input from the user in a while loop. The code works the first time it prompts the user and receives input, but it never works the second time. After the second prompt comes up, no matter what the user types, the program just waits and does nothing even though it's still running. I've been trying to get this to work for hours and have read the Java Docs, many SO questions, etc. Here's the relevant code:
public void gameloop() {
while (thedeck.cards.size() >= 1) {
prompt();
}
}
public void prompt() {
String command = "";
Boolean invalid = true;
System.out.println("Enter a command - h for hit, s for stay, q for quit: ");
Scanner scanner = new Scanner(System.in);
while (invalid) {
if (scanner.hasNext()) {
command = scanner.next();
if (command.trim().equals("h")) {
deal();
invalid = false;
} else if (command.trim().equals("s")) {
dealerturn();
invalid = false;
} else if (command.trim().equals("q")) {
invalid = false;
System.exit(0);
} else {
System.out.println("Invalid input");
scanner.next();
}
}
}
scanner.close();
}
Here's what the code outputs:
Dealer has shuffled the deck.
Dealer deals the cards.
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Enter a command - h for hit, s for stay, q for quit:
h
Dealer deals you a card:
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Queen of Hearts: 10
Enter a command - h for hit, s for stay, q for quit:
h (Program just stops here, you can keep entering characters,
but it does nothing even though the code is still running)
Any idea as to what's going wrong would be greatly appreciated. I also realize the while loop is a little ugly, but I just want to get this program in working condition before I start to revamp any code.

From the documentation for Scanner.close:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Here you close your scanner, and this causes System.In to be closed, which means you can't read any more input:
scanner.close();
It is better to open the scanner once and reuse it. Close it only when are sure you have finished reading all input, or are closing your application.

Related

How do you remove the console output inputted by the user in eclipse?

I want the program to wipe out the previous console output. For example i have a data entry program that when the program repeats, the whole output that were inputted must be wiped away in the console for privacy (for instance, if someone you don't know is using the program again and you don't want them to see what you've inputted in the console before). By the way I am using Java in eclipse and I wonder if this thing would be possible.
String aWord;
String repeat;
do {
Scanner scan = new Scanner(System.in);
System.out.println("Type anything.");
aWord = scan.nextLine();
System.out.println("Do you want to type anything again? Y/N");
repeat = scan.nextLine();
while(!repeat.equalsIgnoreCase("y") && !repeat.equalsIgnoreCase("n")) {
System.out.println("[ERROR] Please answer correctly.");
repeat = scan.nextLine();
if (repeat.equalsIgnoreCase("n")) {
System.out.println("Thanks for using this program!");
System.exit(0);
}
}
if (repeat.equalsIgnoreCase("n")) {
System.out.println("Thanks for using this program!");
System.exit(0);
}
}while (repeat.equalsIgnoreCase("y"));
// if the user answers yes, the program must repeat the whole process.
// if the user answers yes, the program must wipe out all previous output in the console.

Im trying to make a text based game that looks like a PC terminal, i cant find a way to tell the user if they use a wrong sentence

//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}

Incorrect input even though it's a correct input

I'm fairly new to Java and I'm facing some difficulties. So i've been instructed to run a program where you will login in to a system by entering a pin number and school name. You have 3 attempts for each until a message prompts that tells you that the login has failed. My problem is. Everything is fine but in PIN SECTION, (userInputPin==PIN) section, it automatically inputs "Attempt #2 - Enter your school name - Incorrect. upon first correct attempt. When writing the correct school name, it shows login failed as well when it should notify that you have logged in. What's the error?
Note:Ignore comment, I'll fix them.
public class Login {
public static final int PIN = 1234; //Declaring constant for fixed PIN
//Declaring constant for first school name
public static final String FIRST_SCHOOL = "St. Charles";
public static void main(String[] args) {
Scanner kb = new Scanner (System.in); //Declaring scanner object
int attempts = 1; //Declaring variable for attempt number
//Printing first paragraph section of the program
System.out.println("This program simulates logging into a bank account,"
+ "\nasking certain questions for security.\n");
// PIN Section
while(attempts<=3) //While loop
{
System.out.print("Attempt #"+attempts+" - Enter PIN: ");
int userInputPin = kb.nextInt(); //User inputs pin number
//Conditional situations
if(userInputPin==PIN)
{
attempts=1;
while(attempts<=3)
{
System.out.print("\nAttempt #"+ attempts+" - Enter your first school: ");
String userInputSchool = kb.next();
//Conditional situations
if(userInputSchool.equals(FIRST_SCHOOL))
{
System.out.println("\nYou're logged in.");
}
else{
if(attempts==3)
{
System.out.println("\nLogin failed.");
}
else
{
System.out.println("Incorrect.\n");
}
}
attempts++;
}
}
else{
if(attempts==3){
System.out.println("\nLogin failed.");
}
else{
System.out.println("Incorrect.\n");
}
}
attempts++; //Increments attempt by 1 when PIN is incorrect
}
Ah yes, ye ol' Scanner. I can't begin to tell you how many times I've suffered the same problem.
The problem lies in the fact that the nextInt() function sometimes regards the enter key as another token. So when you input the first value, nextInt() recognizes the number inputted. But after printing the second message, the scanner object still has the enter key stored in it. The only way to move forward is to empty the object like so:
if(kb.hasNext()) kb.nextLine();
Insert this after each time you input a number.

How to ask user if he/she wants to quit the program and print out the thank you message in Java

I am taking the first Java class and working on my second project. The project is about creating an program as a network of rooms on a virtual three-dimensional work area. Each room provides a virtual environment that together can be assemble into a simulated or virtual world.
Basically, the beginning of the program, I used while loop, and at the end I want to ask user if he/she wants to quit the program, and print a thank you message. However, the while loop does not work. My program quit no matter I entered y or n. Below is my codes.
import java.util.Scanner;
public class Project
{
public static void main(String[] args)
{
Map map = new Map();
int floor = 0;
int row = 0;
int col = 0;
String input = " ";
Scanner scan = new Scanner(System.in);
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
String choice = "y";
while(!input.equalsIgnoreCase("quit"))
{
input = scan.nextLine().toLowerCase();
// My codes are here
if (input.equals("south")
{statement}
else
System.out.println("You can't go that way.");
else if (input.equals("quit"))
{ // See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
// if user enters other words than quit
else
System.out.println("I don't recognize the word '" + input +"'");
}
System.out.println("Thank you for visiting L.A Underground.");
}
}
When I typed "quit" the console printed the message: "Do you wish to leave the Underground? (Y/N)? >". I tried Y/N (y/n) the program terminated. Any help is appreciated. Thank you.
Updated: Sorry for the confusion. What I wanted the program to run is when the user types "quit", the message will print out "Do you wish to leave the Underground (Y/N)?>?" , and if the user types "hello", the message will be "I don't understand the word 'hello'". And when the user type y, the program will quit, otherwise (type n), the program will start over again.
Ask for user input inside of your loop. If input.equalsIgnoreCase("quit"), then prompt the user an "are you sure" message. If the input.equalsIgnoreCase("y"), then break the loop, otherwise, keep going.
Scanner scan = new Scanner(System.in);
String input;
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
while (true) {
input = scan.nextLine();
if (input.equalsIgnoreCase("quit")) {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
if (scan.nextLine().equals("y")) {
break;
}
}
// input wasn't "quit", so do other stuff here
}
System.out.println("Thank you for visiting L.A Underground.");
Your code loops until it gets "quit" ... then asks for "yes/no" ... then simply exits, regardless.
You need to change your loop, so that it includes BOTH "MY CODES HERE" AND the "quit y/n" check.
EXAMPLE:
...
boolean done = false;
while(!done) {
//MY CODES ARE HERE
if (input.equalsIgnoreCase("quit") && getYesNo ()) == 'y') {
done = true;
}
}
"getYesNo()" is a method you write. For example:
char getYesNo () {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
String line = scan.nextLine();
return line.charAt(0);
}
In the code you've posted, your loop is being controlled by the condition !input.equalsIgnoreCase("quit"). That is, if input is "quit", the loop is terminated.
But the following block is executed only if input is "quit":
if (input.equals("quit"))
{
// See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
So if this block is executed, !input.equalsIgnoreCase("quit") evaluates to false and the loop is terminated. And that's not what you want.
Now that you know what's wrong, fixing it is easy. Check the value of choice in the above if block: if choice is not yes, don't quit i.e. reset input to a default value.
I've pasted the working code here on pastebin.

|| in while loop not working as expected

I'm having an issue that I cannot seem to fix. My goal is to prompt the user for the number of people playing the game. I want to continue prompting the user while their input meets the following requirements:
-input is not an integer
-input is less than three
-input is larger than seven
What is happening is that it seems to require 3 inputs to check the third condition, one for the first and two for the second. It is not checking them all at once, and I assume it has something to do with the syntax .nextInt(), but I cannot find another way to express this. Thank you ahead of time for your help!
Here is the code:
public void setNumPlayers(Game game) {
Scanner input = new Scanner(System.in);
System.out.println("How many people are playing?");
while(!input.hasNextInt() || input.nextInt() < 3 || input.nextInt() > 7) {
System.out.println("Please eneter the number of people playing. You must have at least three players, and no more than seven.");
input.next();
}
game.setNumPlayers(input.nextInt());
input.close();
}
and the call in the main
Game g = new Game();
ConsoleOutput io = new ConsoleOutput();
io.setNumPlayers(g);
System.out.println(g.getNumPlayers());
EDIT:
I've changed the code to store the nextInt as a variable. The following code works, prompts me if I enter letters, prompts me and lets me reassign x if I enter a number outside of its parameters, the only issue is that If I enter an incorrect number, THEN a letter, it crashes...should I encapsulate this in some kind of a try/catch? That doesnt seem practical.
public void setNumPlayers(Game game) {
Scanner input = new Scanner(System.in);
System.out.println("How many people are playing?");
while(!input.hasNextInt()) {
System.out.println("Please eneter the number of people playing.");
input.next();
}
int x = input.nextInt();
while(x<3 || x>7) {
System.out.println("The number of players must be at least three and no more than seven.");
x = input.nextInt();
}
game.setNumPlayers(x);
input.close();
}
You have to modify a little bit the logic, if you want to check input and continue to ask to enter until the input is good. The following will work for a sequence of inputs like:
How many people are playing?
Please enter the number of people playing. You must have at least three players, and no more than seven.
10
Please enter the number of people playing. You must have at least three players, and no more than seven.
toto
Please enter the number of people playing. You must have at least three players, and no more than seven.
tutu
Please enter the number of people playing. You must have at least three players, and no more than seven.
22
Please enter the number of people playing. You must have at least three players, and no more than seven.
6
Scanner input = new Scanner(System.in);
System.out.println("How many people are playing?");
int numPlayers = 0;
while (numPlayers < 3 || numPlayers > 7) {
System.out.println("Please enter the number of people playing. You must have at least three players, and no more than seven.");
if (!input.hasNextInt()) {
input.next();
}
else {
numPlayers = input.nextInt();
}
}
game.setNumPlayers(numPlayers);
input.close();
By calling Scanner.nextInt() twice, you read two numbers, not the same one twice.
Consider reading the int value, store it in a variable and use that in your if statement.
use && operator. and also use a local variable and assign the value from scanner. and use it in condition.
int x =0;
if(input.hasNextInt())
{
x= input.nextInt();
}
while( x > 3 && x < 7) {
System.out.println("Please eneter the number of people playing. You must have at least three players, and no more than seven.");
input.next();
}

Categories

Resources