Question

    String c = JOptionPane.showInputDialog(null,"Pick a conversion to do:\nGrade");
    if (c.equals("grade")||("Grade"))

I want it to start if the user enters grade or Grade not just grade, but when I use this I get a error. How would I fix that

Était-ce utile?

La solution

The actual problem: You're using || improperly. It expects, on both sides, something of type boolean to be present.

From the JLS:

Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs.

Since "Grade" isn't a boolean (but c.equals("grade") is), this becomes a compile-time error.

While you could fix it by correcting the boolean on the right hand side...

if(c.equals("grade") || c.equals("Grade"))

...why not do it in a more straightforward way?

if(c.equalsIgnoreCase("grade"))

This particular equals on String was likely engineered for this use case (or other use cases, as "GrAde" would fail your check too). It will perform a length check on your strings first, then a case insensitive comparison on each element.

Autres conseils

You cannot put an || statement in the middle of a method call like that.

if (c.equals("grade")||c.equals("Grade")){
    //do stuff
}

There are other ways to accomplish your task, IE using other methods, but your problem is coming form a misuse of the || operator.

You can try:

if (c.toLowerCase().equals("grade")) { }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top