Java程式檢查字串是否為空或null
在本文中,我們將學習如何在Java中檢查字串是否為空或null。字串是一種包含一個或多個字元的資料型別,並用雙引號(“ ”)括起來。我們將首先學習如何在main方法中直接檢測這些情況,然後我們將學習如何使用封裝來實現相同的結果,以提高程式碼組織性和可重用性。
問題陳述
編寫一個Java程式來檢查字串是否為空或null。以下是演示:
輸入
Input string: null
輸出
The string is a null string
不同的方法
以下是檢查字串是否為空或null的不同方法:
使用main()方法
以下是使用‘main’方法檢查字串是否為空或null的步驟:
- 建立一個名為Demo的類,其中包含main方法。
- 定義一個字串變數input_string,並將其設定為null或任何您想檢查的值。
- 將input_string的值列印到控制檯以作參考。
- 檢查Null或Empty
- 使用if條件語句檢查input_string是否為null。如果為true,則列印它是null字串。
- 使用else if檢查字串是否為空,使用input_string.isEmpty()。如果為true,則列印它是空字串。
- 使用if條件語句檢查input_string是否為null。如果為true,則列印它是null字串。
- 如果兩個條件都不滿足,則列印該字串既不是null也不是空。
示例
在這裡,我們將所有操作都繫結在‘main’方法下:
public class Demo {
public static void main(String[] args) {
String input_string = null;
System.out.println("The string is defined as: " +input_string);
if (input_string == null) {
System.out.println("\nThe string is a null string");
}
else if(input_string.isEmpty()){
System.out.println("\nThe string is an empty string");
} else {
System.out.println("\nThe string is neither empty nor null string");
}
}
}
輸出
The string is defined as: null The string is a null string
使用封裝
以下是使用封裝檢查字串是否為空或null的步驟:
- 建立一個名為Demo的類,並新增一個靜態方法isNullEmpty,該方法接受一個字串引數input_string。
- 檢查Null或Empty
- 在isNullEmpty中,使用if語句檢查input_string是否為null。如果為true,則列印它是null字串。
- 使用else if使用input_string.isEmpty()檢查字串是否為空。如果為true,則列印它是空字串。
- 否則,列印該字串既不是null也不是空。
- 在isNullEmpty中,使用if語句檢查input_string是否為null。如果為true,則列印它是null字串。
- 在main方法中初始化和測試
- 在main方法中,定義一個字串變數input_string,並將其設定為null。
- 列印input_string的值。
- 使用input_string作為引數呼叫isNullEmpty方法來檢查其狀態。
示例
在這裡,我們將操作封裝到函式中,展現了面向物件程式設計:
public class Demo {
static void isNullEmpty(String input_string) {
if (input_string == null) {
System.out.println("\nThe string is a null string");
}
else if(input_string.isEmpty()){
System.out.println("\nThe string is an empty string");
} else {
System.out.println("\nThe string is neither empty nor null string");
}
}
public static void main(String[] args) {
String input_string = null;
System.out.println("The string is defined as: " +input_string);
isNullEmpty(input_string);
}
}
輸出
The string is defined as: null The string is a null string
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP