java判断数据是否存在语法
时间: 2023-06-12 14:06:35 浏览: 263
Java判断数据是否存在通常有两种方法:
1. 使用if语句:
如果你想要判断一个数组中是否存在某个元素,可以使用以下代码:
```
int[] arr = {1, 2, 3, 4, 5};
int searchNum = 3;
boolean found = false;
for(int i = 0; i < arr.length; i++){
if(arr[i] == searchNum){
found = true;
break;
}
}
if(found){
System.out.println("Number " + searchNum + " is found in the array.");
}else{
System.out.println("Number " + searchNum + " is not found in the array.");
}
```
在这段代码中,我们使用了一个布尔类型的变量found来表示是否找到了要查找的元素。
如果你想要判断一个字符串中是否存在某个子串,可以使用以下代码:
```
String str = "This is a text.";
String searchStr = "text";
boolean found = str.contains(searchStr);
if(found){
System.out.println("Substring " + searchStr + " is found in the string.");
}else{
System.out.println("Substring " + searchStr + " is not found in the string.");
}
```
在这段代码中,我们使用了String类中的contains方法来判断一个字符串中是否包含了某个子串。
2. 使用Collections类中的contains方法:
如果你想要判断一个List中是否存在某个元素,可以使用以下代码:
```
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
if(list.contains(3)){
System.out.println("Number 3 is found in the list.");
}else{
System.out.println("Number 3 is not found in the list.");
}
```
在这段代码中,我们使用了List中的contains方法来判断一个集合中是否包含了某个元素。如果集合中包含了元素3,那么contains方法将会返回true。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)