问题
I have an unexpected issue when using a conditional operator in java.
The code is supposed to check if the ArrayList
contains a specific string, then it returns true or false. It is not the first time I do this, but for some reason there's something wrong.
This is my code so far:
public boolean isDone() {
ArrayList<String> al = new ArrayList<String>(); //Defining ArrayList
al.add(d1.getText()); // Adding the text from JLabels.
al.add(d2.getText());
al.add(d3.getText());
al.add(d4.getText());
al.add(d5.getText());
if(al.contains(".")) {
return false;
} else {
return true;
}
The issue is that when running the debugger, it should return false
and instead of that, it returnstrue
. For some reason the conditional is not "reading" the content of the ArrayList, or stuff like that.


As you see, the ArrayList contains the .
that needs the conditional to return false, but instead of that, it returns true. What is wrong in my code?
回答1:
Try this:
public boolean isDone() {
ArrayList<String> al = new ArrayList<String>();
al.add(d1.getText());
al.add(d2.getText());
al.add(d3.getText());
al.add(d4.getText());
al.add(d5.getText());
for (String str : al)
if (str != null && str.contains("."))
return false;
return true;
}
You have to check each string individually, the contains()
method in ArrayList
will return true
only if the exact string "."
is present in the list, not if one of the strings in the list contains a dot.
回答2:
When you use a1.contains(...), you are checking if any sting in array is ".". This is different from your intention to check if any string in array "a1" contains '.' char as I understand.
If you need to check if any string in array contains "." text it can be like this:
for(String text : a1) {
if(text != null && text.indexOf(".") >= 0) {
return false;
}
}
return true;
回答3:
Your List<String>
does not contain the String
that equals "."
. You have a String that contains a .
but that is not the same thing. You can do that with String.contains(CharSequence),
public boolean isDone() {
List<String> al = new ArrayList<String>(); // <-- I would use the Interface type
al.add(d1.getText());
al.add(d2.getText());
al.add(d3.getText());
al.add(d4.getText());
al.add(d5.getText());
// If any String in al contains a '.' return false, else true.
for (String str : al) {
if (str.contains(".")) {
return false;
}
}
return true;
}
来源:https://stackoverflow.com/questions/24580239/simple-conditional-in-java-unexpected-issue