[英]Boolean, if methods,
我是Java編程語言的初學者。 我無法編寫該程序的代碼,因為我不是布爾運算符的專家。 我只是想知道你們那里的人如何在書中編寫這個問題,因為我無法弄清楚如何在沒有if / else分支的情況下使這個程序正常工作。 我們將不勝感激,如果您對此問題感到惱火,將不勝感激。
書中的問題,
編寫一個程序,要求用戶輸入月份(1表示1月,2表示2月,依此類推),然后打印該月的天數。 對於2月,請打印“ 28天”。
Enter a month: 5
30 days
將Month類與方法一起使用public int getLength()請勿每個月使用單獨的if / else分支。 使用布爾運算符。
謝謝!
*我不知道如何使用switch語句,我只是想像書中所說的那樣去做,
謝謝
假設您不需要處理leap年,您的Month
班級可能看起來像這樣:
public class Month {
private int monthNumber;
public Month(int monthNumber) {
if (monthNumber < 1 || monthNumber > 12) {
throw new IllegalArgumentException(
"Month number must be between 1 and 12");
}
this.monthNumber = monthNumber;
}
public int getLength() {
return monthLengths[monthNumber - 1]; // indexes start at 0
}
private static int[] monthLengths = {
31, // January
28, // February
31, // March
. . .
}
}
其余的代碼(提示用戶,獲取輸入,錯誤檢查,打印答案)留作練習。 :)
PS我根本無法想象Boolean
在哪里輸入。
如果您想為指定數字做某事,可以使用類似
if ( number == 1 ){
doSomething();
} else if ( number == 3 ){
doSomething();
} else if ( number == 5 ){
doSomething();
}
但是由於這種方法是被禁止的
請勿每個月使用單獨的if / else分支。
使用布爾運算符。
您需要使用布爾值OR ||
像
if (number==1 || number == 3 || number == 5){
doSomething();
}
現在嘗試使用幾個月。
我願意做這樣的事情:
public class Month
{
int month;
public Month(int _month)
{
this.month = _month;
}
public int getLength()
{
if(this.month == 2) { return 28 }
if(this.month<8)
{
if((this.month%2) == 1)
{
return 31
}
else
{
return 30
}
}
else
{
if((this.month%2) == 1)
{
return 30
}
else
{
return 31
}
}
}}
編輯。 閱讀本書中更新的問題后,我認為他們正在尋找類似的內容。
public int getLength()
{
if(this.month == 2) {return 28;}
if(this.month == 1 || this.month == 3 || this.month == 5 || this.month == 7 || this.month == 8 || this.month == 10 || this.month ==12){ return 31;}
if(this.month == 4 || this.month == 6 || this.month == 9 || this.month == 11){return 30;}
}
但是其他人給出的答案在現實生活中會更好。
使用映射,鍵為用戶輸入的整數,值為該月的天數。 例如:
Hashmap<Integer, Integer> map = new Hashmap<Integer, Integer>();
map.put(1, 31);
...
map.put(12, 31);
然后要求輸入並執行以下操作:
int input = ...;
if (map.containsKey(input)) {
System.out.println(map.get(input));
}
else {
System.out.println("Invalid month input");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.