Comparing char in a while loop --- condtion is never met - java

So I have a really annoying problem which I am hoping one of you could help solve for me. This is a really simple program that prints my COMP science username in asterisks. I have attached a choice for the user - to either print the username in asterisks or simply print the characters.
I have constructed a while loop that validates the data entered by the user is accurate. The conditions for this while loop are never met - so it always loops through it no matter what is entered. I'm sure this is a really simple problem, just haven't really used chars before so can't figure out what I am doing wrong.
//===================================================== START OF MAIN
public static void main (String [] args){
Scanner input = new Scanner(System.in); // Scanner for users input
char usersChoice = 0; // Variable for users input
System.out.println("\nWould you like to see the large letters or the small letters?\n (Enter L for large, S for small!!)\n");
usersChoice = input.next().charAt(0); // Users Input
System.out.println(usersChoice);
//================================================= WHILE LOOP TO CHECK AUTHENTICITY OF DATA
while (usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' || usersChoice != 'S'){
System.out.println("\nWrong Input - Please try again!!!\n");
usersChoice = input.next().charAt(0);
System.out.println(usersChoice);
}//end of while
//================================================= IF (CHAR = L) PRINT BIG LETTERS
if (usersChoice == 'L' || usersChoice == 'l'){
printU();
print4();
printJ();
printA();
}//end of if
//================================================= ELSE PRINT LETTERS
else{
System.out.println("\nU");
System.out.println("4\n");
System.out.println("J\n");
System.out.println("A\n");
}//end of else
}//end of main

The while statement expression is always true since not all expressions can be true at once - you need the conditional && operator
while (usersChoice != 'l' && usersChoice != 'L' && usersChoice != 's' && usersChoice != 'S') {

Your logical or(s) should be logical and(s), this
while (usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' ||
usersChoice != 'S')
Should be
while (usersChoice != 'l' && usersChoice != 'L' && usersChoice != 's' &&
usersChoice != 'S')
The problem with your while loop is there is no character that could meet the conditions. Consider lower case l, when the usersChoice is l it's not L so it wouldn't finish.

while (!(usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' || usersChoice != 'S'))
Just add an exclamation mark before your while-loop.
Your while-loop always do not work because:
if userChoice is 'l', it is not 'L'/'s'/'S' (expression is true)
if userChoice is 'L', it is not 'l'/'s'/'S' (expression is true)
if userChoice is 's', it is not 'l'/'L'/'S' (expression is true)
if userChoice is 'S', it is not 'l'/'L'/'s' (expression is true)
Your while-loop always evaluates to true

Related

Java, How to close do-while loop using multiple character boolean expressions?

This is quite a beginner question but I'm wondering why my do...while loop is not closing.
The program is supposed to loop while the user input is not 'C', 'c', 'F', or 'f'.
It seems to close when just one boolean expression in the while section is valid but not if multiple are valid.
public class CelsToFaren
{
public static void main(String[] args)
{
// scanner setup
Scanner sc = new Scanner(System.in);
// Variable declarations
int celsius;
int answerC;
int farenheit;
int answerF;
char userLetter;
do
{
// initial menu options
System.out.println("Which temperature would you like to convert from? ");
System.out.println(" >(C)elsius ");
System.out.println(" >(F)arenheit ");
// user input of C, c, F, or f to select option
userLetter = sc.next().charAt(0);
// if user input C or c
if ((userLetter == 'C' || userLetter == 'c'))
{
System.out.print("Please enter the temperature: ");
celsius = sc.nextInt();
answerC = ((celsius*9/5)+32);
System.out.println("The answer is: " + answerC + " Farenheit ");
}
else
{
// if user input F or f
if ((userLetter == 'F' || userLetter == 'f'))
{
System.out.print("Please enter the temperature: ");
farenheit = sc.nextInt();
answerF = ((farenheit-32)*5/9);
System.out.println("The answer is: " + answerF + " Celsius ");
}
else
{
// if user input not F, f, C, or c
if ((userLetter != 'F' || userLetter != 'f' || userLetter != 'C' || userLetter != 'c'));
{
System.out.println("Please enter a valid option");
}
}
}
} while ((userLetter != 'c') || (userLetter != 'C') || (userLetter != 'f') || (userLetter != 'F'));
}
}
You need to change the exit logic.
In your case 1 | 0 | 0 = true so the loop continues.
You need to change it to:
while ((userLetter != 'c') && (userLetter != 'C') && (userLetter != 'f') && (userLetter != 'F'));
Your condition is wrong. Lets assume you want to break loop in if statement. It would look like
if(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F')
Now let's apply negation to get a condition under which you do not need to exit the loop
if(!(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F'))
this condition is simillar to
if(userLetter != 'c' && userLetter != 'C' && userLetter != 'f' && userLetter != 'F')

So I need to find all vowels in a string and replace them using a loop

So I have this and be aware that I only use simple methods such at toString(), charAt. Right now my code is just returning the original string, and I do not know why.
Ok, so I realized that after a few tests, the reason it is returning the original string is because in the nested if statement in the loop, the condition is never true, so it bypasses the if statement. Why is it never true?
System.out.print("Enter in a string: ");
String userInput = scan.nextLine();//string user enters
String vowelChar;//individual character within user's input
for (int i=0; i<userInput.length(); i++){
Character indChar = userInput.charAt(i);
vowelChar = indChar.toString();
if (vowelChar=="a" || vowelChar=="e" || vowelChar=="i" || vowelChar=="o" || vowelChar=="u"){
String beforeText = userInput.substring(0, i-1);//string before vowel
String afterText = userInput.substring(i+1);//string after vowel
userInput=beforeText+"_"+afterText;
}else{
//character is not a vowel
//do nothing
}
}
System.out.print(userInput);
}
}
A few things to consider:
Don't use "==" when comparing Strings, as explained in: Why doesn’t == work on String?
You can compare chars with "==", so you shouldn't need to convert it to a String for the comparison.
The index in your for loop starts at 0, so this statement:
String beforeText = userInput.substring(0, i-1)
will throw a java.lang.StringIndexOutOfBoundsException if there is a vowel at the first index.
You don't need the "else" case if you aren't doing anything inside it.
Although this isn't how I would implement the kind of loop you wanted, here is a solution that works with the least amount of changes to your original code:
System.out.print("Enter in a string: ");
String userInput = scan.nextLine();//string user enters
for (int i = 0; i < userInput.length(); i++) {
Character indChar = userInput.charAt(i);
if (indChar == 'a' || indChar == 'e' || indChar == 'i' || indChar == 'o' || indChar == 'u' ||
indChar == 'A' || indChar == 'E' || indChar == 'I' || indChar == 'O' || indChar == 'U') {
String beforeText = userInput.substring(0, i); //string before vowel
String afterText = userInput.substring(i + 1); //string after vowel
userInput = beforeText + "_" + afterText;
}
}
System.out.print(userInput);
Instead of converting back to String and comparing with == (since we compare the value of Strings via Object#equals), use the char type for your comparison using if/switch. Additionally you should compare in a singular casing so as not to have A and a not match.
char c = Character.toLowerCase(userInput.charAt(i)); //make the character lowercase
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
//replace vowel
break;
}
There is no need to convert to a String. Compare characters directly
Character indChar = userInput.charAt(i);
if ((vowelChar == 'a' || vowelChar == 'e' || vowelChar == 'i' || vowelChar=='o' || vowelChar=='u') {
// ...
}
Note the char in single quotes and not double quotes
Change your code like this
if (vowelChar.equals("a") || vowelChar.equals("e") || vowelChar.equals("i") || vowelChar.equals("o") || vowelChar.equals("u")){
Or
if (indChar =='a' || indChar =='e' || indChar =='i' || indChar =='o' || indChar =='u'){
String a = "abcde";
Character indChar = a.charAt(0);
String vowelChar = indChar.toString();
System.out.println("vowelChar Char: " + vowelChar);
System.out.println(vowelChar == "a"); printed false
System.out.println(vowelChar.equals("a")); printed true
So use equals instead of ==

Having difficulty ignoring case sensitivity for do while loop

Trying to let the user exit the program using the letter 'N' or 'n' but it will only let them exit when using 'N'
Below is my code, any help is appreciated!!
System.out.print(" Do you want to repeat the ");
System.out.println("program ['Y' or 'N']");
Choice = sc.next().charAt(0);
} while (Choice != 'N' || Choice != 'n');
}
}
You have to use while (Choice != 'N' && Choice != 'n'); .
It must be AND condition. Not an OR condition.
You are using the wrong operator:
while (Choice != 'N' && Choice != 'n');
Right now, your code states that the loop will continue when the character is either not 'N' or not 'n'. Since the character can't be 'N' and 'n' at the same time, the loop will always continue. Switching the operator to a && requires that the character is neither N nor n to continue.

Java - charAt(), equalsIgnoreCase, if statement testing?

What I want is no matter what the user inputs, if the first letter of their input is either a 'y' or 'n' regardless of case, it will print "game start".
I've tried equalsIgnoreCase() with the "letter" variable but it gives the error: char cannot be dereferenced. Any recommendations will be really appreciated on this! Thanks!
Scanner input = new Scanner(System.in);
System.out.println("Do you want to continue?");
String wesker = input.nextLine();
char letter = wesker.charAt(0);
if(letter == 'y' || letter == 'p'){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
Try use Character#toLowercase():
if (Character.toLowerCase(letter) == 'y' || Character.toLowerCase(letter) == 'n') {
or
if (Character.toUpperCase(letter) == 'Y' || Character.toUpperCase(letter) == 'N') {
or simply
if( letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N' )
Just check against both cases:
if( letter == 'y' || letter == 'Y' || letter == 'p' || letter == 'P' )
equalsIgnoreCase can be used only by Strings. For your case, if you want to use that method, you can do this:
Scanner input = new Scanner(System.in);
String wesker = input.nextLine();
String letter = wesker.substring(0,1);
if(letter.equalsIgnoreCase("y") || letter.equalsIgnoreCase("n")){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
You could pre-build a set of acceptable characters.
Set<Character> yes = new HashSet<>(Arrays.asList('y','Y','p','P'));
public void test() {
char letter = 'c';
if ( yes.contains(letter)) {
}
}

Loop has gone crazy

This loop keeps giving me my error message even when I enter a valid input and I can't find what is wrong with it. It's the same as my other loops in the program which all work fine. Does anyone know the problem? Here is the loop:
System.out.println("Male or Female (M/F)");
gender = userInput.next().charAt(0);
gender = Character.toLowerCase(gender);
while((gender != 'm') || (gender != 'f')) {
System.out.println("ERROR Please enter a valid age");
System.out.println("Male or Female (M/F)");
gender = userInput.next().charAt(0);
gender = Character.toLowerCase(gender);
}//end while
Now if I type 'm' or 'f' it will give me the error message? ??? ???
while((gender != 'm') || (gender != 'f')) {
should really be
while((gender != 'm') && (gender != 'f')) {
The condition (gender != 'm') || (gender != 'f') always evaluates to true. To understand why, consider one case - gender = 'm'...
(gender != 'm') || (gender != 'f')
('m' != 'm') || ('m' != 'f')
false || true
true
Basically, java doesn't know the common English idiom if gender isn't (either) male or female.

Categories

Resources