Java: bad operand types
•
Java
I'm a beginner. I'm sorry if this question is stupid
I wrote the following code:
public class Traindata { String City; public Traindata(String t_city) { if(t_city == "Judenburg" || "Knittelfeld" || "Zeltweg" || "Leoben" || "Bruck/Mur" || "Kapfenberg") { City = t_city; } else { System.out.println("City not allowed: " + t_city + "\n"); }
All I have to do is check t_ Is the city the same as one of the allowed cities (judenburg, knitelfeld, zeltweg, Leoben)
But when I try to compile the code, I receive this error message: "error: bad operand type '|' of binary operator"
So can anyone help me? I think I'm wrong with "𞓜", but I can't make it work
E: Thank you. I didn't even know that equals () existed
Solution
There are two problems in your code: you need to use equals to compare Java strings, and you need to reuse comparisons to construct | expressions:
if(t_city.equals("Judenburg") || t_city.equals("Knittelfeld") ... )
Better, construct a HashSet < string > city you want to match, and use the inclusion method to check the conditions:
Set<String> cities = new HashSet<String>(Arrays.asList( "Judenburg","Knittelfeld","Zeltweg","Leoben","Bruck/Mur","Kapfenberg" )); ... if (cities.contains(t_city)) { ... }
This is a demo of this later approach on idea
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码