我對for回圈中的條件有疑問,我不明白,我知道它的作用,但我不能理解代碼條件的邏輯,誰能給我解釋一下這個條件的邏輯:
if(smallWord == null || bigWord.compareTo(smallWord)<0)
if(smallWord == null || bigWord.compareTo(smallWord)<0)/code>
/*2. 輸入執行此功能的Exercise2類。
1. 指示用戶輸入一個數字[至少四(4):使用while回圈],表示有多少個
字/句子,并使用for回圈要求用戶輸入這些字/句子。
2. 找到并在控制臺顯示哪個詞/句子最小(按字母順序排在前面)。*/
import java.util.Scanner。
public class Exercise2 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in)。
System.out.println("輸入一個大于4的數字")。
int size = scan.nextInt()。
while (size < 4) {
System.out.println("輸入一個大于4的數字")。
size = scan.nextInt();
}
scan.nextLine()。
String smallWord = null。
for (int i = 0; i< size; i ) {
System.out.println("Shtypni fjaline e " (i 1) " 。")。)
String bigWord = scan.next() 。
if (smallWord == null || bigWord.compareTo(smallWord) < 0) {
smallWord = bigWord。
}
}
System.out.println("按字母順序最小的單詞/句子是。" smallWord)。)
}
}
uj5u.com熱心網友回復:
這個條件確保bigWord將被分配給smallWord如果:
smallWord == null
或者
bigWord比smallWord'小'(因為compareTo()如果字串在詞典上比引數小,則回傳一個小于0的值)
uj5u.com熱心網友回復:
整個for回圈的目的是為了找到詞譜上最小的詞。 這樣做的方法是將每個新詞(bigWord)與目前發現的最小的詞(smallWord)進行比較。
所以if測驗說 "如果到目前為止還沒有找到最小的詞,或者這個新詞比到目前為止找到的詞小,那么這個新詞就是我們現在擁有的最小的詞"。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/328920.html
標籤:
