Why is my or operator not working in my while loop

50 views Asked by At

Im trying to use an or operator the the parameters of my while loop and its not working.

import javax.swing.JOptionPane;

public class Checkpoint203P5 {
public static void main(String[] args){
    String inputString;
    String letter;

    inputString = JOptionPane.showInputDialog(null, "Please enter Y or N", "Not case sensitive");
    letter = inputString;

    while(!inputString.equals("Y" || "N")){
        JOptionPane.showMessageDialog(null, "You did not enter Y or N. \n       Please try again",  "Warning", 2);
        inputString = JOptionPane.showInputDialog(null, "Please enter Y or N", "Not case sensitive");
    }

    JOptionPane.showMessageDialog(null, "Thank you for participating");
    System.out.println("End of Job");
}
    
}

I tried replacing the || with + but then it made it so that I have to put "YN" or it would be invalid.

1

There are 1 answers

0
Milos Stojanovic On

In Java, the || operator cannot be used between strings as you attempted. The || operator is used for performing logical disjunction (OR) between two boolean expressions. It cannot directly work with strings.

In your original attempt:

while (!inputString.equals("Y" || "N"))

the expression "Y" || "N" is not valid in Java because the || operator expects two boolean expressions (or boolean values) on its left and right sides.

Instead, you need to compare each string separately using the || operator:

while (!inputString.equals("Y") && !inputString.equals("N"))

This expression checks if inputString is different from "Y" and different from "N". If it is, the loop will continue to execute. If inputString is equal to "Y" or "N", the loop will stop.

Little offtopic:

In JavaScript, the logical operator || can be used with "truthy" expressions, including strings. When you use the || operator between two expressions, it returns the first "truthy" expression. If the first expression evaluates to "truthy" (not false, null, undefined, 0, NaN, or an empty string ''), then that expression will be returned, and the second expression will not be evaluated.