Issues with Do/While loop in java - java

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!

Related

How do I make sure that the input is not null and that only one character is being entered?

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);
}
}

How to escape this while-loop

I wrote the following method, which boolean-return type is again assigned to another boolean in another method in which I call this method.
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while(answer != "y" || answer != "n") {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer == "y") {
b = true;
}
return b;
}
But no matter what I type in (y, n, or any other letter), I always end up in the while-loop again.
It's because you have an or rather than and on your test.
As it's currently coded you are saying:
while the answer isn't "y" or it isn't "n", loop.
which will always be the case.
What you want is:
while the answer isn't "y" and it isn't "n", loop.
which is coded as:
while (answer != "y" && answer != "n") (
Change to this: while(answer != "y" && answer != "n") and your code will work as you expect it to.
I suspect your problem lies here:
while(answer != "y" || answer != "n")
When your answer = "y" it isn't = "n" so the loop continues and vice verse.
Probably you want this:
while(answer != "y" && answer != "n")
I changed your code a bit to accept a char instead.
Here is the code:
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
char answer = input.nextLine().toLowerCase().charAt(0);
while(answer != 'y' || answer != 'n' ) {
System.out.println("Answer with y (yes) or n (no)");
//lower case so that it will get y or n, no matter what the casing is
answer = input.nextLine().toLowerCase().charAt(0);
}
if (answer == 'y') {
b = true;
}
return b;
}
or if you really want a string
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while( !(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n")) ) {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer.equalsIgnoreCase("y")) {
b = true;
}
return b;
}
Remember to use .equals() or .equalsIgnoreCase() when comparing two Strings

Trying to create "Play Again" for a game in Java

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;
}

In need to create a java program that uses a loop to check if a password is correct. The program runs but the output isn't correct [closed]

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 8 years ago.
Improve this question
Any time I enter a password whether it is in valid format or invalid format, it always outputs "Invalid password".
import java.util.Scanner;
public class PasswordTest
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
boolean length = true;
boolean digit = true;
boolean lowercase = true;
boolean uppercase = true;
char ch = 0;
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch = s1.charAt(i);
if (Character.isDigit(ch)){
digit = true;
}
if (Character.isLowerCase(ch)){
lowercase = true;
}
if (Character.isUpperCase(ch)){
uppercase = true;
}
if (s1.length()>=8){
length = true;
}
}
if (digit==false && lowercase==false && uppercase==false && length==false)
System.out.println("Valid password");
else
System.out.println("Invalid password");
}
}
You need to first set all the boolean values to false at the time of declaration, and then in the code below set it to true only if it satisfies the condition. Also while printing "Valid Password" check if all boolean values are true, else print "Invalid Password". Checking if string length is greater than 8 should be outside the loop body. Following code works.
import java.util.Scanner;
public class PasswordTest
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
boolean length = false;
boolean digit = false;
boolean lowercase = false;
boolean uppercase = false;
char ch=0;
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch = s1.charAt(i);
if (Character.isDigit(ch)){
digit = true;
}
if (Character.isLowerCase(ch)){
lowercase = true;
}
if (Character.isUpperCase(ch)){
uppercase = true;
}
}
if (s1.length()>=8){
length = true;
}
if (digit==true && lowercase==true && uppercase==true && length==true)
System.out.println("Valid password");
else
System.out.println("Invalid password");
}
}
What you did is first set the boolean value to true then again in loop you are setting it to true which doesnot makes sense.I think this code will work fine for you
Scanner input = new Scanner(System.in);
boolean length = false;
boolean digit = false;
boolean lowercase = false;
boolean uppercase = false;
char ch = '\u0000';
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch = s1.charAt(i);
if (Character.isDigit(ch)){
digit = true;
}
if (Character.isLowerCase(ch)){
lowercase = true;
}
if (Character.isUpperCase(ch)){
uppercase = true;
}
if (s1.length()>=8){
length = true;
}
}
if (digit==true && lowercase==true && uppercase==true && length==true)
System.out.println("Valid password");
else
System.out.println("Invalid password");
For the future, I think regular expressions would be helpful.
Your password requirements seem to be "8 or more characters in length, where each character may be a lowercase letter, a capital letter, or a digit," is that right? We can express those requirements with a regular expression, such as ([a-z]|[A-Z]|[0-9]){8,}. With this, we may write
String password = input.nextLine();
if(password.matches("([a-z]|[A-Z]|[0-9]){8,}") {
// Go about your business.
}
I have a question for you, if it can't it be lowercase and if it cant be uppercase then what could it be? I made it so it has to be lowercase, here is the code (if you want it to be all uppercase then change this if statement in the code if(digit[i] == true || lowercase[i] == false || uppercase[i] == true) to if(digit[i] == true || lowercase[i] == true || uppercase[i] == false)
import java.util.Scanner;
public class PasswordTest{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
boolean length;
boolean pass = true;
String s1;
//Prompt user to enter password
System.out.print("Enter password: ");
s1 = input.nextLine();
boolean[] digit = new boolean[s1.length()];
boolean[] lowercase = new boolean[s1.length()];
boolean[] uppercase = new boolean[s1.length()];
char[] ch = new char[s1.length()];
//Check what ch is
for (int i=0; i<s1.length(); i++){
ch[i] = s1.charAt(i);
digit[i] = Character.isDigit(ch[i]);
lowercase[i] = Character.isLowerCase(ch[i]);
uppercase[i] = Character.isUpperCase(ch[i]);
}
length = s1.length()>=8;
if (length==false && s1.length() > 0) {
int i;
for(i = 0; i < s1.length(); i ++){
if(digit[i] == true|| lowercase[i] == false|| uppercase[i] == true)
pass = false;
}
if(pass == true)
System.out.println("Valid password");
else{
System.out.println("Invalid password");
}
}else{
System.out.println("Invalid password");
}
}
}

Java issue with scanner

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;
}
}

Categories

Resources