java - 为什么无法识别布尔值?
问题描述
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 我希望它打印“找不到产品”。
解决方案
由于您未初始化的布尔变量,我认为这不会编译。在长度为 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;
}
}
}
推荐阅读
- python - 为什么我的 Google Maps API 请求的填充速度如此缓慢?
- javascript - 在一加 7 Pro [React-Native] 中截屏时,Android 应用程序崩溃
- audio - Flutter - 录音 - 用户点击录音按钮时如何根据频率实现正弦波形?
- android - 如何使用睡眠循环动画
- ios - 使用三个键 Swift 5 过滤 Firebase QueryDocumentSnapshot 数组
- java - 在使用 iText 编写 pdf 时确定 i18n 的动态字体
- javascript - 获取 DOM 的文本值并显示在 dat.gui 字段中
- xml - 使用包含命名空间的 SQL-SERVER-2016 从 XML 中检索数据
- php - 如何从子域嵌套文件夹中删除 index.php
- oracle - PLS-00049 BAD BIND VARIABLE 在具有特定排序规则的列上的触发器上