data validation using char != not working [duplicate] - java

This question already has answers here:
Java char comparison does not seem to work [duplicate]
(2 answers)
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed last year.
Hello I know this is so basic but I am having trouble in comparing char specifically with the !=. Whenever I input other letter (not y and n) code still loop.
I tried changing the != to == and when i press Y it gets out of loop.
How is this happening? Thank you!
public static void main(String[] args) {
char inputChar;
Scanner input = new Scanner(System.in);
do {
System.out.println("-----------------------------------------------");
System.out.println("Try Again(Y/N)? ");
do {
inputChar = input.next().toUpperCase().charAt(0);
System.out.println("Loop");
} while (inputChar != 'Y' || inputChar != 'N');
System.out.println(inputChar + " d");
} while (inputChar == 'Y');
System.out.println("Thank you and Good bye!");
}

while (inputChar != 'Y' || inputChar != 'N');
The condition you wrote says 'loop while the input is not Y or is not N'.
No character is equal to Y and equal to N at the same time, so this will loop forever.
If it's Y, then it's not N, so the second part is true.
If it's N, then it's not Y, so the first part is true.
If it's Z, then both parts are true.
You want
while (inputChar != 'Y' && inputChar != 'N');

The issue is with this line: } while (inputChar != 'Y' || inputChar != 'N');
Since you are using a logical or operation, the loop continues while inputChar is not equal to Y or inputChar is not equal to N. The issue is that one of these is always true so your loop runs forever since a character cannot be both equal to 'N' and to 'Y'. Try using a logical and (&&) instead.

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')

Error "The operator == is undefined for the argument type(s) char, boolean"

I'm trying to do this:
System.out.println("Do you want to solve an equation (y/n)?");
char first = In.getChar();
boolean y = true;
boolean n = false;
if(first == y)
System.out.println("Enter a:");
if(first == n)
System.out.println("Thanks");
Basically, what I'm trying to do is that if I ask the user to solve the equation and the user presses y (meaning yes), then it will go through the if statement for which y is true; but if the user enters n (meaning no), then it will say something like "thanks for using the system".
I'm getting the error "The operator == is undefined for the argument type(s) char, boolean".
What am I doing wrong, and how can I fix this?
y is a boolean. 'y' is a char
if (first == 'y') {
...
}
You're comparing the different data types char and boolean and Java doesn't know how to do that. For example, what should be the result of this?
'a' == false
If you want to compare the content of a char variable with a specific char then do the following:
char charVar = 'n';
if (charVar == 'y') { // this would return "false", because 'n' is not equal 'y'
//...
}
So you can change your code as follows:
if(first == 'y')
System.out.println("Enter a:");
else if(first == 'n') // use "else if" instead of "if" :)
System.out.println("Thanks");

Java char comparison does not seem to work [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed last year.
I know you can compare chars in Java with normal operators, for example anysinglechar == y. However, I have a problem with this particular code:
do{
System.out.print("Would you like to do this again? Y/N\n");
looper = inputter.getChar();
System.out.print(looper);
if(looper != 'Y' || looper != 'y' || looper != 'N' || looper != 'n')
System.out.print("No valid input. Please try again.\n");
}while(looper != 'Y' || looper != 'y' || looper != 'N' || looper != 'n');
The problem should not be the other method, inputter.getChar(), but I'll dump it anyway:
private static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
public static char getChar() throws IOException{
int buf= read.read();
char chr = (char) buf;
while(!Character.isLetter(chr)){
buf= read.read();
chr = (char) buf;
}
return chr;
}
The output I'm getting is as follows:
Would you like to do this again? Y/N
N
NNo valid input. Please try again.
Would you like to do this again? Y/N
n
nNo valid input. Please try again.
Would you like to do this again? Y/N
As you can see, the char I put in is an n. It is then printed out correctly(hence it is to be seen twice). However, the comparison doesn't seem to become true.
I'm sure I'm overlooking something obvious.
Your logic is incorrect. It is always true that looper isn't 'Y' or it isn't 'y' or it isn't ...
You want the logical operator for "and": &&
if(looper != 'Y' && looper != 'y' && looper != 'N' && looper != 'n')
and a similar change in your while condition.
Rather than fix the logic operator from || to &&, make the code clearer:
private static final Set<Character> YES_OR_NO = Set.of('Y', 'y', 'N', 'n');
do {
System.out.print("Would you like to do this again? Y/N\n");
looper = inputter.getChar();
System.out.print(looper);
if (!YES_OR_NO.contains(looper))
System.out.print("No valid input. Please try again.\n");
} while(!YES_OR_NO.contains(looper));

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