Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator || or | cannot be used

Tags:

java

I am trying to get this code to compile, but my compiler (BlueJ)is telling me the || cannot be applied to java.lang.string.java.lang.string

import java.io.*;
import javax.swing.JOptionPane;

class Hi {
public static void main (String [] args){

String Answer;
Answer = JOptionPane.showInputDialog("Who is a troll?");
if (Answer.equals ("null")) 
{
 JOptionPane.showMessageDialog(null, "You forgot to enter an answer before pressing 'ok'.");
} 
else if (Answer.equals("Bob" || "Bob" || "Charlie Sheen"))
{
JOptionPane.showMessageDialog(null, "Your answer is incorrect.");
} 
else
JOptionPane.showMessageDialog(null, "Yes, " + Answer + ", is definitely a douchebag.");

System.exit(0); // not needed to run 

}
}

Thank you sooo much for the help

like image 917
Mot39 Avatar asked Dec 02 '22 00:12

Mot39


1 Answers

You can't do it like that. The || operator expects two boolean operands, and yours are strings. You have to check each equality separately:

if (answer.equals("Bob") || answer.equals("Charlie Sheen")) {
}

A few sidenotes:

  • variable names should be lowercase (by convention).
  • you shouldn't supply the same string ("Bob") twice.
  • null is not the same as "null". You should compare answer == null. If you try to call .equals(..) on a null object, you'll get an exception
like image 76
Bozho Avatar answered Dec 17 '22 09:12

Bozho