For some reason, with this code, tests that I've run shows that the program entirely skips the nextLine request for an input from the user and it registers as blank space for its first iteration. Afterwards it'll go back to the beginning of the while loop and take an input, but no matter what I type in it (whether it's y or Y for yes, N or n for no) it'll go to the else statement. I don't understand what I'm doing wrong, help!
private static boolean promptForPlayAgain(Scanner inScanner) {
boolean play = true;
int test = 0;
while(test == 0)
{
System.out.println("Would you like to play again [Y/N]?:");
String input = inScanner.nextLine();
System.out.println(input);
if (input == "y" || input == "Y")
{
test++;
}
else if (input == "n" || input == "N")
{
play = false;
test++;
}
else
{
System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
}
}
return play;
}
With the tips from what you guys said I've edited and ran my code which now works. Thanks a lot guys!
private static boolean promptForPlayAgain(Scanner inScanner) {
boolean play = true;
int test = 0;
while(test == 0)
{
System.out.println("Would you like to play again [Y/N]?:");
inScanner.nextLine();
String input = inScanner.nextLine();
if (input.equals("y") || input.equals("Y") )
{
test++;
}
else if (input.equals("n") || input.equals("N") )
{
play = false;
test++;
}
else
{
System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
}
}
return play;
}
Related
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
b = scan.next().charAt(0);
if (Character.toString(b).matches("^[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I have this method that checks whether the input is a letter in the alphabet or not, but I want to make sure that the input from the user is not null and that the user only enters one letter. For example "A" or "a" is a correct char, the problem is if I enter "Abcdef" then it is still true as the first letter is still a valid char. I want to make it so that the user can only enter one char, I think I've done that by using the scanner and charAt(0) but is there a more efficient way to do it, and I'm also not sure how to make it so that the input isn't null.
I've revised your code to do what you wanted:
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
EDIT
Without scanner (see comments):
public static boolean correctchar(char b, String input) {
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I made couple of changes :
If invalid input ask user to enter again.
Make sure to close the scanner scan.close()
Scanner scan = new Scanner(System.in);
System.out.println("Please enter only one character : ");
String input = scan.next();
while (null == input || input.isEmpty() || input.length() > 1) {
System.out.println("Invaid Input, Please enter only one character : ");
input = scan.next();
}
scan.close();
if (Character.toString(input.charAt(0)).matches("^[a-zA-Z]")) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
public static boolean correctChar() {
try (Scanner scan = new Scanner(System.in)) {
String input = null;
do {
input = scan.next();
if (input != null && input.length() == 1) {
boolean isCorrect = input.matches("[a-zA-Z]");
System.out.println(isCorrect ? "True" : "False");
return isCorrect;
} else {
System.out.println("Insert only one character");
}
} while (true);
}
}
Coding a simple HiLo card game where the user is given a card value from a deck of cards and then inputs 'higher', 'lower' or 'equal' trying to guess the balue of the next card.
Just really can't get my head around user input validation with iteration ie. not moving on until a string with the required parameters has been entered.
My code so far:
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
Random randomCard = new Random();
int numberOfSuccesses = 0;
boolean finished = false;
int card = (randomCard.nextInt(13) + 2);
while (finished != true) {
int nextCard = (randomCard.nextInt(13) + 2);
String pictureCard = "";
if (((numberOfSuccesses < 0) ? nextCard : card) == 11) {
pictureCard = "Jack";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 12) {
pictureCard = "Queen";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 13) {
pictureCard = "King";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 14) {
pictureCard = "Ace";
}
System.out.println("The card is a " + ((card > 10) ? pictureCard : card));
if (numberOfSuccesses == 4) {
System.out.println("Congratulations. You got them all correct");
finished = true;
break;
}
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
String userGuess = reader.nextLine().toLowerCase();
//TODO validate input
if (userGuess.equals("higher")) {
if (nextCard > card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("lower")) {
if (nextCard < card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("equal")) {
if (nextCard == card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
}
System.out.println(numberOfSuccesses);
card = nextCard;
}
if (numberOfSuccesses < 4) {
System.out.println("Sorry, incorrect!");
}
}
}
and the relevant code extract:
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
It kinda just gets stuck at the above part giving "Try again" over and. I've completed programs having to use .hasNextInt() but I'm struggling with this string validation.
Thanks for any and all help/comments!
You are calling reader.nextLine() up to 3 times and so you are comparing 3 different strings.
If I enter "xxx" your code says "xxx != higher so read another line" - it never compares "xxx" to "lower" or "equal".
Also pay attention to && vs ||.
Solution is to read one line into a variable and use that variable for each condition. I'm not going to write it out as this is clearly homework or a self learning exercise, so best for you to do it yourself.
I think your condition logic needs to change. You are checking if input not equal to "higher" or not equal to "lower" or not equal to "equal" so it will always be false overall even if you enter expected value - if you enter "higher" it's not equal to lower. You need to change ors to ands.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In my java code below:
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + userName + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
Before the loop is entered the block of code:
else {
System.out.println("Invalid response.");
}
is executed. Can someone point out why this is happening or whats wrong?
Edit: The keyboard Scanner is used before in this block of code as well
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + userName + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
Thanks for the replies, I fixed it by replacing "keyboard.nextLine();" with "keyboard.next();"
This might be one of the reason that is happening with your code . You have already taken a UserInput from the keyboard object of the scanner class that's why it's giving the else response. This particularly happens when you take other than String input from that object
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
int n=keyboard.nextInt();
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
Output
5
Invalid response.
now change the code structure to get String Input from that scanner Object and not get another kind of data types the code works.
With String as previous Input
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
String n=keyboard.nextLine();
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
Output
j
y
Great! Let's get started.
Without any previous response with that object your code will work.
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
and Gives me the desired output
y
Great! Let's get started.
I usually have been doing this whole time creating two OBJECT of Scanner Class one to get String Input and other to get other data types Input
(Too be frank even i have been not able to figure out why i needed to create two Object's for receiving String and Other data types in java without any error. If anyone know please let me know )
In my opinion, the Boolean variable is having value as false, and first character user is entering is not 'n' - hence the else-if block is getting executed.
I don't know how your code look like.
Considering the sample attached i had written the below code which doesn't enter the else block first
else {
System.out.println("Invalid response.");
}
Please verify your code with the below and comment back!
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String userResponse = "";
Scanner keyboard = new Scanner(System.in);
while (true) {
System.out.println("Please Enter Your Input");
userResponse = keyboard.nextLine();
if (userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
} else if (userResponse.length() == 1
&& userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + userResponse + ".");
System.exit(0);
} else {
System.out.println("Invalid response.");
}
}
}
}
Output :
Please Enter Your Input
yes
Invalid response.
Please Enter Your Input
no
Invalid response.
Please Enter Your Input
y
Great! Let's get started.
It would be good if you can post the whole code! If you are still facing the issue!
This code is a snippet from a Blackjack game I'm making. No matter what I enter, the program never breaks out of a loop.
boolean bool = true;
do{
Scanner kb = new Scanner(System.in);
String choice = kb.next();
if(choice == "Hit" || choice == "hit") {
String action = "hit";
bool = false;
} else if(choice == "Stay" || choice == "stay") {
String action = "stay";
bool = false;
} else {
System.out.println("Do not recognize response. Retry.");
}
} while (bool == true);
What normally happens:
http://puu.sh/87KZk.png
Any help would be appreciated. Thanks!
You are comparing strings with ==. In Java we compare strings with .equals() instead.
You can do something like this:
boolean bool = true;
do {
Scanner kb = new Scanner(System.in);
String choice = kb.next();
if(choice.equals("Hit") || choice.equals("hit")) {
String action = "hit";
bool = false;
} else if(choice.equals("Stay") || choice.equals("stay")) {
String action = "stay";
bool = false;
} else {
System.out.println("Do not recognize response. Retry.");
}
} while (bool == true);
I also formatted some parts of your code for clarity.
As suggested in the comments below, you can also use equalsIgnoreCase to compare string regardless of their capitalization.
Hope this helps!
I have a method that should scan for one of 3 letters in caps or lowercase and return the lower case version of the letter. If an improper letter is entered the user is warned and reasked for a letter. I have two issues, 1: as soon as the method is run I get the outputted line with the error message telling the user invalid entry without waiting for an entry! (so the second the method is run I see High, low or sevens (H/L/S):Invalid entry. Please try again using H/L/S! before entering anything then the method is recalled again and all works fine form there except for my next issue) 2: the entry that is gotten from the scanner never passes any of my if statements even though it should.
my code:
private static char getHighLow(Scanner inScanner) {
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
return 'h';
}
else if (entered.equals("L") || entered.equals("l")){
return 'l';
}
else if(entered.equals("S") || entered.equals("s")){
return 's';
}
char result = 0;
while(result != 'l' || result != 'h' || result != 's'){
System.out.println("Invalid entry. Please try again using H/L/S!");
result=getHighLow(inScanner);
}
return result;
}
Instead of using while(), you can use 'else' like this-
private static char getHighLow(Scanner inScanner) {
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
return 'h';
}
else if (entered.equals("L") || entered.equals("l")){
return 'l';
}
else if(entered.equals("S") || entered.equals("s")){
return 's';
}
else {
System.out.println("Invalid entry. Please try again using H/L/S!");
return getHighLow(inScanner);
}
}
You can simply use equalsIgnoreCase and trim the entered string. And add a while loop util your condition is satisfied.
Scanner scanner = new Scanner(System.in);
boolean loop = true;
String choice = null;
while (loop) {
System.out.print("High, low or sevens (H/L/S):");
choice = scanner.nextLine();
if ("H".equalsIgnoreCase(choice.trim())
|| "L".equalsIgnoreCase(choice.trim())
|| "S".equalsIgnoreCase(choice.trim())) {
System.out.println("Correct Choice");
loop = false;
}
else
{
System.out.println("Wrong Choice");
}
}
System.out.print(choice);
char result;
while(true){
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
result = 'h';break;
}
else if (entered.equals("L") || entered.equals("l")){
result = 'l';break;
}
else if(entered.equals("S") || entered.equals("s")){
result = 's';break;
}else{
System.out.println("Invalid entry. Please try again using H/L/S!");
}
}
Hey you are not breaking out of the while loop at all. Did you see that ?
This is what you want. Here is the program to iterate over characters in a String. And convert them in lower case letter if they are H,L OR S.
package testproj;
import java.util.Scanner;
public class TestProj {
public static void main(String[] args) {
Scanner scanner = new Scanner("HLs");
String result = getHighLow(scanner);
System.out.println("Result :"+result);
}
private static String getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S):");
String entered;
String result = "";
boolean isCharFound = false;
String temp = "";
while (inScanner.hasNext()) {
temp = inScanner.next();
System.out.println(temp);
for (int index = 0; index < temp.length(); index++) {
entered =new Character(temp.charAt(index)).toString() ;
if (entered.equals("H") || entered.equals("h")) {
result = result + 'h';
isCharFound = true;
} else if (entered.equals("L") || entered.equals("l")) {
result = result + 'l';
isCharFound = true;
} else if (entered.equals("S") || entered.equals("s")) {
result = result + 's';
isCharFound = true;
}
if (!isCharFound) {
System.out.println("Invalid entry. Please try again using H/L/S!");
}
isCharFound = false;
}
}
return result;
}
}