Reputation: 1
I'm having a terribly tough time with this simple code. My while conditions are always ignored and the print statement is executed. Please help.
package Checkpoints;
import java.util.Scanner;
public class Check05 {
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
/**
* Write an input validation that asks the user to enter 'Y', 'y', 'N', or 'n'.
*/
String input, Y = null, N = null;
System.out.println("Please enter the letter 'Y' or 'N'.");
input = keyboard.nextLine();
while (!input.equalsIgnoreCase(Y) || !(input.equals(N)))
//|| input !=y || input !=N ||input !=n)
{
System.out.println("This isn't a valid entry. Please enter the letters Y or N" );
input = keyboard.nextLine();
}
}
}
Upvotes: 0
Views: 5557
Reputation: 33
Add this extra conditions before "while" loop to avoid this
if(Y!= null && !Y.isEmpty())
if(N!= null && !N.isEmpty())
Upvotes: 0
Reputation: 567
Change this;
String input, Y = null, N = null;
to this;
String input, Y = "Y", N = "N";
So that you can compare the user input string with "Y" and "N" strings.
And this;
while (!input.equalsIgnoreCase(Y) || !(input.equals(N)))
to this;
while (!(input.equalsIgnoreCase(Y) || input.equalsIgnoreCase(N)))
because your design of condition is misaimed, as @talex warned.
Upvotes: 1
Reputation: 3638
You are comparing the input to null
since you forgot to define the values of the string Y
and N
.
You can define the answer values in constants like so:
public static final String YES = "y";
public static final String NO = "n";
public static void main (String[] args) {
Scanner keyboard;
String input;
keyboard = new Scanner(System.in);
System.out.println("Please enter the letter 'Y' or 'N'.");
input = keyboard.nextLine();
while (!(input.equalsIgnoreCase(YES) || input.equalsIgnoreCase(NO))) {
System.out.println("This isn't a valid entry. Please enter the letters Y or N" );
input = keyboard.nextLine();
}
}
EDIT: corrected the while condition as suggested by talex
Upvotes: 0