Java中的简单条件(意外问题) [英] simple conditional in java (unexpected issue)

查看:97
本文介绍了Java中的简单条件(意外问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中使用条件运算符时遇到意外问题. 该代码应该检查ArrayList是否包含特定的字符串,然后返回true或false.这不是我第一次这样做,但是由于某种原因,这是有问题的.

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;
   }

问题在于,运行调试器时,它应返回false,而不是返回true.由于某种原因,条件条件未读取" ArrayList或类似内容.

The issue is that when running the debugger, it should return falseand instead of that, it returnstrue. For some reason the conditional is not "reading" the content of the ArrayList, or stuff like that.

如您所见,ArrayList包含.,它需要条件才能返回false,但取而代之的是,它返回true.我的代码有什么问题?

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?

推荐答案

尝试一下:

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;

}

您必须单独检查每个字符串,仅当列表中存在确切的字符串"."时,ArrayList中的contains()方法将返回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.

这篇关于Java中的简单条件(意外问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆