error: bad operand types for binary operator '=='

3.2k Views Asked by At

Just wanted to do a task in my Book but I don't get why this is wrong.It should say that negative Numbers aren't positive and positive aren0t negative with a Boolean. This is my Code:

import javax.swing.JOptionPane;

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

        String eingabe;
        char Zahl;
        boolean istVokal;
        eingabe = JOptionPane.showInputDialog("Geben Sie eine Zahl ein: ");
        if (Zahl == "- && Zahl") {
            istVokal = false;
        } else {
            istVokal = true;
        }
        if (istVokal == true) {
            JOptionPane.showMessageDialog(null, "Die Zahl ist nicht negativ!");
        } else {
            JOptionPane.showMessageDialog(null, "Die Zahl ist negativ!");
        }
    }
}

I don't know what I am doing wrong ... pls help. This is error code:

Zahlentest.java:10: error: bad operand types for binary operator '=='
            if (Zahl == "- && Zahl") {
             ^
      first type:  char
      second type: String
    1 error
3

There are 3 best solutions below

1
e4c5 On BEST ANSWER

Zahl is a char that you are trying to compare to a String. In java that is not allowed though there are other languages where it is indeed allowed.

if(Zahl == '-') 

Maybe what you are looking for but I still doubt it because Zahl isn't initialized at that stage. I think what you are really looking for is

if (eingabe.equals("- && Zahl"))

As a foot note, let me point out that we don't start field names or variable names with upper case characters. We generally use camelCase for that

0
AudioBubble On

You compare char with String, that's why the error. The operands of the binary operator '==' must be of the same type.

0
sn42 On

You can't compare the string - && Zahl to the character in the variable Zahl with the operator == because in java a char is a primitive type while a String is an object.

By the way: You did not assign a value to Zahl, i dont understand what your intention is by comparing it to the string.