Multiple conditions in WHILE loop - java

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.

Related

How to write a continuous (infinite loop) program in JAVA to verify vowel?

Write a program that asks the user to type a vowel from the keyboard. If the character entered is a vowel, display “OK”; if it is not a vowel, display an error message. Be sure to allow both uppercase and lowercase vowels. The program continues until the user types ‘!’.
I have written the program but I need it to loop. I wrote a code where it only accepts one input and I don't know what I am supposed to use for the input for char.
Scanner input = new Scanner(System.in);
System.out.println("Enter an alphabet between a to z; Enter ! to stop");
int myChar;
myChar = input.nextInt();
while (myChar <= 'z') {
if (myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u' ) {
System.out.println(myChar + " OK");
} else {
System.out.println(myChar + " is not vowel");
}
}
You're almost there :)
A small error that you've made is that you've limited your scanner to only reading integers.
You've also declared myChar to an int. Since it is a character, you can declare it like:
char myChar = input.next().charAt(0);
A scanner has many functions, and some are specific to certain variable types
.nextInt() will only read integers.
nextDouble().will read doubles
.nextLine() will read till the end of the current line
Thus, as I mentioned above, you can simply use .next().charAt(0)
First, you need to put the declaration before you give it a value, so it should be
int myChar;
myChar = input.nextInt();
Second, you are reading a char, so it should not be int myChar...
char myChar;
myChar = input.next().charAt(0);// Since there no nextChar() in scanner
Third, your while loops is NEVER going to stop, since the value of myChar is not changed in the while loop,
Fourth, you did not allow both uppercase and lowercase vowels, you only allowed lowercase vowels
Fifth, add the statement "! to stop", I mean, I'm sure you don't want "! is not a vowel" to be printed, right?
So this is what it should look like:
Scanner input= new Scanner(System.in);
System.out.println("enter alphabet between a & z, ! to stop");
char myChar;
myChar = input.next().charAt(0);
while(('a' <= myChar && myChar <= 'z') || ('A' <= myChar && myChar <= 'Z')) {
if(myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u' || myChar == 'A' || myChar == 'E' || myChar == 'I' || myChar == 'O' || myChar == 'U'){
System.out.println(myChar + " OK");
}else if(myChar == '!'){
break;
}else{
System.out.println(myChar + " is not vowel");
}
System.out.println("Enter again:");
myChar = input.next().charAt(0);
}
You code is almost correct but you are missing few very important parts.
Declaration int myChar; should be written before initialization myChar = input.nextInt();
You are willing to read a char so you should declare myChar variable with data type char and not int.
Your while-loop condition does not satisfy the need. Because you are just using one end of the range of alphabet but missing the other end and hence it will not generate desired boolean result.
Approach to reach solution for your problem:
Read a string from user using scanner.next() method.
Convert the string to lower case to handle upper and lower case vowels.
Take the first character from the read string input by using the method string.charAt(0) to convert String into char and save it to myChar.
Start a while-loop that will keep iterating until myChar == '!'.
Inside the loop, first check if myChar is a vowel. If true, print "OK".
If myChar is not a vowel, check if myChar fall in range of an alphabet or not. If true, print "Not a vowel".
If myChar does not fall in the range of English alphabets then print "You entered an incorrect alphabet" and prompt for new value.
Finally, if myChar is !, then the condition for while-loop becomes false and the program stops.
Here is the full code:
Scanner input = new Scanner(System.in);
System.out.println("Enter an alphabet between 'a' to 'z'; Enter '!' to terminate");
/*
* input.next() reads a string from Scanner's input stream until it finds a space or endOfLine.
* string.toLowerCase() converts any English alphabet in a string to lower case and return the new string. For example, "Hello World 21F" becomes "hello world 21f".
* string.charAt(0) returns the character of a string at index 0; 1st position.
*/
char myChar = input.next().toLowerCase().charAt(0);
while (myChar != '!') {
if (myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u') {
System.out.println(myChar + " OK");
} else if (myChar >= 'a' && myChar <= 'z') {
System.out.println(myChar + " is not vowel");
} else {
System.err.printf("You entered an incorrect alphabet '%c'. ", myChar);
}
System.out.println("Enter an alphabet between 'a' to 'z'; Enter '!' to terminate");
myChar = input.next().toLowerCase().charAt(0);
}

Using || OR Operator within If Statements alongside characters

I'm very new to programming in general, and I'm having a bit of trouble with a program I'm writing in Java to help calculate my final grade in a class. This part of the program asks me what letter grade I would like to receive, and then determines if that input is valid. For example, if I typed into the keyboard that I wanted to receive a letter grade of "Z", because that is not a valid grade, I would like my program to output "Invalid Input" and exit. The code I have written below is not producing any syntax errors, but it outputs "Invalid Input" for every letter grade I choose, even A, B, and C (inputs that should be valid). Any help in understanding what's wrong is more than welcome.
Scanner input = new Scanner(System.in);
char desiredGrade
System.out.print("What letter grade do you want to achieve for the course? ");
desiredGrade = input.next().charAt(0);
if (desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'){
System.out.println("Invalid Input");
System.exit(0);
}
In addition to this, it would be helpful to not have to worry about case sensitivity with the inputs. I know I can use .ignoreCase() or .equalsIgnoreCase() with strings, but I'm not quite sure how to implement that with char.
see this Answer
For Upper- and Lowercase you can wrap your char in Character and then call toLowerCase and check the input and the expected value on Lowercase.
In your example
desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'
If you want to use the || operator you have to do it like that
if(!(desiredGrade == 'A' || desiredGrade == 'B' || desiredGrade == 'C')){
}
That way you check if the Input is A, B, or C and if not then exit
Lets say desiredGrade = 'A'
if (desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'){
The first condition will be false, but the second and third will be true. So
if (false || true || true)
Will result always in true.
The way to do it is using operator AND &&
if (desiredGrade != 'A' && desiredGrade != 'B' && desiredGrade != 'C'){
This way, if the user decides to input 'A' the operation will be
if (false && true && true){
Resulting in false. And if the user inputs 'Z', the operation will be
if (true && true && true){
That will result true and execute the Invalid input output.
EDIT
As it has been mentioned. The user may input 'a' (lowercase) for which condition desiredGrade = 'A' will be false since 'a' != 'A' (is not equal).
So it will be wise to convert desiredGrade to uppercase before the if statement.
Try out
(desiredGrade != 'A' && desiredGrade != 'B' && desiredGrade != 'C')
Basically, you want to check if desiredGrade is different than A and different than B and different than C, print out invalid input.
Try this:
if (! Arrays.asList ('A', 'B', 'C').contains (Character.toUpperCase (desiredGrade))) {
// your error handling
}

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

Categories