列印偶數長度單詞的Java程式
在本文中,我們將瞭解如何列印偶數長度的單詞。字串是一種資料型別,包含一個或多個字元,並用雙引號 (“ ”) 括起來。字元是一種資料型別,包含字母、整數或特殊字元。
問題陳述
編寫一個Java程式來列印偶數長度的單詞。下面是演示:
輸入
Input string: Java Programming are cool
輸出
The words with even lengths are: Java cool
列印偶數長度單詞的方法
以下是列印偶數長度單詞的不同方法:
使用基本方法列印偶數長度單詞
以下是使用基本方法列印偶數長度單詞的步驟:
- 開始
- 宣告一個字串變數input_string併為其賦值。
- 使用split(" ")方法將input_string分割成單個單詞。
- 使用for迴圈迭代每個單詞。在迴圈內,使用if語句使用word.length() % 2 == 0檢查單詞長度是否為偶數。
- 如果條件為true。
- 顯示結果
- 結束
列印偶數長度單詞的Java程式
在這裡,我們將所有操作繫結在main函式下:
public class EvenLengths { public static void main(String[] args) { String input_string = "Java Programming are cool"; System.out.println("The string is defined as: " + input_string); System.out.println("\nThe words with even lengths are: "); for (String word: input_string.split(" ")) if (word.length() % 2 == 0) System.out.println(word); } }
輸出
The string is defined as: Java Programming are cool The words with even lengths are: Java cool
使用面向物件方法列印偶數長度單詞
以下是使用基本方法列印偶數長度單詞的步驟:
- 開始
- 建立一個靜態方法printWords(),它接受一個字串引數input_string。
- 在printWords()內部,使用split(" ")方法將input_string分割成單個單詞。
- 使用for迴圈迭代每個單詞。
- 使用if語句使用word.length() % 2 == 0檢查單詞長度是否為偶數。
- 如果條件為true,則列印單詞。
- 在main方法中,宣告input_string並呼叫printWords()方法。
- 結束
使用面向物件程式設計列印偶數長度單詞的Java程式
在這裡,我們將操作封裝到函式中,展現了面向物件程式設計:
public class EvenLengths { public static void printWords(String input_string) { System.out.println("\nThe words with even lengths are: "); for (String word: input_string.split(" ")) if (word.length() % 2 == 0) System.out.println(word); } public static void main(String[] args) { String input_string = "Java Programming are cool"; System.out.println("The string is defined as: " + input_string); printWords(input_string); } }
輸出
The string is defined as: Java Programming are cool The words with even lengths are: Java cool
廣告