不幸的是,我的導師不會讓我爲此作業使用列表。如何限制空值存儲在我的數組中?
我想限制空值存儲在我的數組中。我試圖使用if語句,但它不起作用。
public static void main(String[] args) {
System.out.println(messages(3, 10));
}
public static String message(int n) {
String message = null;
if ((n % 3 != 0) && (n % 5 != 0)){
message = null;
} else if((n % 3 == 0) && (n % 5 == 0)) {
message = n + ": FizzBuzz";
} else if (n % 3 == 0) {
message = n + ": Fizz";
} else if (n % 5 == 0) {
message = n + ": Buzz";
}
return message;
}
public static String[] messages(int start, int end) throws IllegalArgumentException {
if (end < start) {
throw new IllegalArgumentException();
} else {
String[] msgArray = new String[end - start];
int j = 0;
for(int i = start; i < end; i++) {
String theMsg = message(i);
/* Where I need help */
// I'm trying to use the if statement to restrict
//all null values from being stored in my msgArray */
if(theMsg != null) {
msgArray[j] = theMsg;
}
j++;
}
System.out.println();
for(String s: msgArray) {
System.out.println(s);
}
return msgArray;
}
}
所需的輸出
3: Fizz
5: Buzz
6: Fizz
9: Fizz
實際輸出
3: Fizz
null
5: Buzz
6: Fizz
null
null
9: Fizz
如果你不希望打印'null',然後把周圍的'System.out的一個'if'。 println'來防止'null'被打印。 – ajb
嘿。我不希望它們存儲在數組中。所以當我使用for each循環打印msgArray時,我仍然會看到上面的「Actual Output」。 –
你的代碼看起來很可疑。你在哪裏用msg填充msgArray [j]? – CCC