Why is ((ans != 'N') || (ans != 'Y')) always true? - java

I'm trying to prompt the user to spin again and my "while" expression is always coming back as false... Anyone have any ideas?
reSpin = false;
if (reSpin == false){
System.out.println("Would you like to spin again? Y/N");
char ans = in.next().charAt(0);
if (ans == 'Y'){
reSpin =true;
}else if (ans == 'N'){
System.out.println("Thank you for playing!");
}else {
while ((ans != 'N') || (ans != 'Y')) {
System.out.println("Invalid answer, please only enter Y/N");
System.out.println("Would you like to spin again? Y/N");
ans = in.next().charAt(0);
}
}
}

You probably want to use:
while ((ans != 'N') && (ans != 'Y')) {
That checks to see that ans is not N and not Y. If you use || (or) there, then it will check to see that ans is either not N, or not Y (which is true for any value of ans).

Pretty simple: According to your comparison, ans would have to be Y and N at the same time.

|| returns true if either one of the expressions on either side is true.
If ans is Y, then ans != 'N' is true, so the whole expression (ans != 'N') || (ans != 'Y') is true. If ans is N, then ans != 'Y' is true, so the whole expression is true.
You want (ans != 'N') && (ans != 'Y'), which says "ans is not 'N' and ans is also not 'Y'."

ans cannot be both 'N' and 'Y' at the same time, so it is always either not equal to 'N' or not equal to 'Y'. You might want to change it to:
while ((ans != 'N') && (ans != 'Y'))
This makes sure that it is both not equal to 'N' and not equal to 'Y'.

Related

Java: it keeps saying "variable yn might not have been initialized" [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 3 years ago.
I already initialized the variable yn, but it keeps saying that I didn't. Tried to initialized it directly on the scanner but it has error and say again that it's already been initialized in the method.
import java.util.Scanner;
public class sample
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int num;
char yn;
while (yn == 'Y' && yn == 'y')
{
do
{
System.out.print("Enter a positive integer: ");
num = s.nextInt();
if (num < 0)
{
System.out.print(num + "is a negative integer. Please try again!");
}
else
{
if (num % 2 == 0)
{
System.out.println(num + " is an even number.");
}
else
{
System.out.println(num + " is an odd number.");
}
continue;
}
}
while (num < 0);
System.out.println("Press Y if you want to input again and N if no.");
yn = s.next().charAt(0);
do
{
if (yn == 'N' && yn == 'n')
{
System.out.println("Done!");
break;
}
else if (yn == 'Y' && yn == 'y')
{
System.out.println("Done!");
continue;
}
else
{
System.out.println("Invalid Input! Try again!");
break;
}
}
while (yn != 'Y' && yn != 'y' && yn != 'N' && yn != 'n');
}
}
}
You declare yn without an initial value and then immediately use it as loop condition.
char yn;
while(yn == 'Y' && yn == 'y'){
would imply you expect a default value of y (or Y). You must explicitly set it so for that to be true. Also, no character is both 'Y' and 'y' so you need a logical or. Like,
char yn = 'Y';
while(yn == 'Y' || yn == 'y') {
You might also consider
char yn = 'Y';
while (Character.toUpperCase(yn) == 'Y') {
and then you don't need an ||. You have the same logical impossibility here
if(yn == 'N' && yn == 'n'){
System.out.println("Done!");
break;
}
else if(yn == 'Y' && yn == 'y'){
System.out.println("Done!");
continue;
}
and can fix it with || (or with Character.toUpperCase(char)).
char yn;
This is where you declare the variable.
while(yn == 'Y' && yn == 'y'){
This is where you use the variable. Nowhere in between these two lines is yn initialized - that's why it's used uninitialized.
Think of "Yn" as a container, you need to have something in the container if you want to test what is inside that container, or in this case
char yn;
Should become
char yn = 'Y';
You test with your while loop and your if statements
char yn; //You are DECLARING a variable
char yn = 'Y' //You are Initialising a variable
In your case, you can say
char yn = ' ';
Because I believe that is what you tried to do
I also noticed you are trying to test if your yn variable is a capital and lowercase at the same time, you can fix this by changing the && (AND) to || (OR)
In Java whenever you declare a variable but do not initialize it (like in your case char yn;), the compiler checks for its initialization part further.
If you later initialize it inside any scope which has a condition (like in your case while (yn == 'Y' && yn == 'y'){..}), then compiler is not able to decide at compile time that whether the code inside the scope or block will get executed or not.
Hence there is no assurance to compiler although you have initialized inside the block.
Therefore compiler throws an error stating, variable not initialized.

Why is this causing a constant 'true' in this while loop?

Here is the code;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N.");
char a = input.next().charAt(0);
// This while loop always comes out as true.
while (a != 'y' || a != 'n') {
System.out.println("Please enter either Y/N. ");
System.exit(0);
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Is there an explanation on why it always comes out as true, and is there an alternative way of doing this? I want to have a validation check, where if the user inputs anything other than y, or n, the program shuts down.
The problem is, when I enter the character, y, or n, it shuts down anyway even though I'm using the != (not equals) operator.
If you have a==y, then a != 'n' is true and a != 'y' || a != 'n' is true.
If you have a==n, then a != 'y' is true and a != 'y' || a != 'n' is true.
If you have a == other thing, a != 'y' || a != 'n' is true.
It is everytime true with the OR operation. Need use AND.
(a != 'y' || a != 'n') at least one of the sub-conditions must be true.
Consider the three possible cases:
a is 'y': false || true gives true
a is 'n': true || false gives true
a is something else: true || true gives true
The character a cannot both be y and n, so the while loop is executed for any input.
Besides, the loop is not looping.
You're checking whether a is not equal to 'y' OR a is not equal to 'n'.
This is always true.
Change it into while ((a != 'y') && (a != 'n')).
The condition inside while in
while (a != 'y' || a != 'n')
is always true because
if a is equal to y, then a is obviously not equal to n. So, result is true.
And again, if a is equal to n, then a is obviously not equal to y. So, result is true.
And again, if a is not equal to y or n, then also the result is true.
So, the condition inside the while is always true. And for this reason, the execution is entering the while loop and after printing your message it is exiting.
So using AND instead of OR may solve your problem, like
while(a != 'y' && a !='n') {
//your work
}
And I think you willing to do this like below,
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N: ");
char a = input.next().charAt(0);
while (a != 'y') {
if(a =='n') {
System.exit(0);
}
else{
System.out.println("Please enter either Y/N : ");
a = input.next().charAt(0);
}
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Your logic should be "a is not y and a is not n"
while (a != 'y' && a != 'n')

Validating a inputted char variable. Do-while loop will not break

I have a method that checks if the user is a student, but I can't get it validate the conditions.
char custStud = '0';
Scanner input = new Scanner(System.in);
do{
System.out.println("Are you a student? (Type Y or N): ");
custStud = input.next().charAt(0);
custStud = Character.toLowerCase(custStud);
}
while (custStud != 'y' || custStud != 'n');
When I fire up this program, it does not break the loop, even if 'y' or 'n' are entered. I suspect custStud might have accidentally changed types when changed to lowercase, but I'm not sure.
How can I make this loop work properly?
while (custStud != 'y' || custStud != 'n') is always true, since custStud can't be equal to both 'y' and 'n'.
You should change the condition to:
while (custStud != 'y' && custStud != 'n')
You've mistaken here:
while (custStud != 'y' || custStud != 'n');// wrong
while (custStud != 'y' && custStud != 'n');// correct
Try running this code:
char custStud = '0';
Scanner input = new Scanner(System.in);
do{
System.out.println("Are you a student? (Type Y or N): ");
custStud = input.next().charAt(0);
custStud = Character.toLowerCase(custStud);
}
while (custStud != 'y' && custStud != 'n');
System.out.print("\n answer:"+custStud);

Java While-Loop Program

I am trying to get a valid input of "y", "Y", "n" , or "N".
If the input is not valid (for example any word that starts with a "y" or "n") I want it to re-prompt the user for input.
So far I have:
while (again.charAt(0) != 'N' && again.charAt(0) != 'n' && again.charAt(0) !='Y' && again.charAt(0) != 'y' ) {
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
if (again.charAt(0)== 'N' || again.charAt(0) == 'n') {
active = false;
} else {
if (again.charAt(0)== 'Y' || again.charAt(0) == 'y'){
active = true;
random = (int) (Math.random () *(11));
}
}
The problem I am having is if I enter any word that starts with the letter "y" or "n" it senses it as valid input (since it is the character at slot 0). I need help fixing this so I can re-prompt the user when they enter a word that starts with a "y" or "n".
Thanks!
Assuming again is a string containing the complete user input, you could use:
while (!again.equals("N") && !again.equals("n") ...
The .equals() method will match only if the entire string matches.
You could just test to make sure the length of the input is 1:
again.length() == 1
But a better approach might be:
while (! (again.equalsIgnoreCase("n") || again.equalsIgnoreCase("y"))) {
...
}
or even
while (! again.matches("[nyNY]")) {
...
}
One of the way would be:
First check again String length is only ONE character. If not, ask again.
if(again.length() ==1)
{
while (again.charAt(0) != 'N' && again.charAt(0) != 'n' && again.charAt(0) !='Y' && again.charAt(0) != 'y' ) {
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
.....
}else
{
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
It sounds like what you want is:
while (!again.equals("N") && !again.equals("n") && !again.equals("Y") && !again.equals("y") ) {
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
This way you can also easily add Yes/No, etc later if you want.
Regex could be an alternative to have strict input checks. Following piece of code validates y or n ignoring the case.
while (!again.matches("(?i)^[yn]$")){
System.out.println ("Invalid Inpur! Enter Y/N");
again = numscan.next();
}
active = (again.equalsIgnoreCase("Y"))? true : false;

Multiple conditions in WHILE loop

I want to exit the while loop when the user enters 'N' or 'n'. But it does not work. It works well with one condition but not two.
import java.util.Scanner;
class Realtor {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
char myChar = 'i';
while(myChar != 'n' || myChar != 'N'){
System.out.println("Do you want see houses today?");
String input = sc.next();
myChar = input.charAt(0);
System.out.println("You entered "+myChar);
}
}
}
You need to change || to && so that both conditions must be true to enter the loop.
while(myChar != 'n' && myChar != 'N')
Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.
Use myChar != 'n' && myChar != 'N' instead
If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Categories