首页 > 解决方案 > 为什么无法识别布尔值?

问题描述

public class HelloWorld {

    public static void main(string[] args) {
        boolean found;
        String[] caseArray = new caseArray {
            "apple", "orange", "mango", "pineapple"
        } ;
        for (int i = 0; i < caseArray.length; i++) {
            if (caseArray[i].equals("pineapple")) {
                found = true;
                break;
            } else {
                found = false;
            }
        }
        if (found == true) {
            System.out.println("product found");
            break;
        } else {
            System.out.print("product not found");
            break;
        }
    }
}

在上面的代码中,当 for 循环在数组中搜索菠萝时,我想返回 found = true。如果 found 等于 true,我希望它打印“找到的产品”,如果 found = false 我希望它打印“找不到产品”。

标签: java

解决方案


由于您未初始化的布尔变量,我认为这不会编译。在长度为 0 的数组的情况下,找到的布尔值永远不会被初始化,Java 不会让你这样做

public class HelloWorld{

    public static void main(string [] args){

    boolean found = false;

    String [] caseArray = new caseArray{"apple", "orange", "mango", "pineapple" };

    for(int i = 0; i< caseArray.length; i++){

                                    if(caseArray[i].equals(pineapple)){

                                        found = true;
                                        break;
                                    } else{

                                        found = false;
                                    }

                                }

                                if(found == true){

                                    System.out.println("product found");
                                    break;

                                } else {
                                    System.out.print("product not found");
                                    break;
                                }    

    }
}

推荐阅读