我被要求編寫一些基於某些指令的程序(類)。我覺得我幾乎崩潰了,但我正在做一些愚蠢的事情。我無法弄清楚如何將一個連字符添加到符號常量中,以便當我輸入INSERT_HYPHEN時,它會在訪問器方法中插入一個「 - 」。它說不兼容的類型> :(當我嘗試將本地變量「fullDate」插入到'getFullDate'訪問器方法中,然後放置「fullDate =年+月+日」時,它表示'不兼容的類型!也許是因爲這accesor方法是一個字符串,我想裏面添加它的整數。「我找不到辦法解決它。這裏是我的代碼。這個程序爲什麼不工作
public class Date
{
public static final int INSERT_ZERO = 0;
public static final char INSET_HYPHEN = -; //ERROR incompatible types
// instance variables - replace the example below with your own
private int year;
private int month;
private int day;
/**
* Default constructor
*/
public Date()
{
setYear (2013);
setMonth (01);
setDay (01);
}
/**
*
*/
public Date (int whatIsYear, int whatIsMonth, int whatIsDay)
{
setYear (whatIsYear);
setMonth (whatIsMonth);
setDay (whatIsDay);
}
/**
*@return year
*/
public int getYear()
{
return year;
}
/**
*@return month
*/
public int getMonth()
{
return month;
}
/**
*@return day
*/
public int getDay()
{
return day;
}
/**
*@return
*/
public String getFullDate()
{
String fullDate;
if (whatIsMonth < 10); // the year, month, and day all give me incompatible types :(
{
fullDate = year + INSERT_HYPHEN + INSERT_ZERO + month + INSERT_HYPHEN + day;
}
if (whatIsDay < 10);
{
fullDate = year + INSERT_HYPHEN + month + INSERT_HYPHEN + INSERT_ZERO + day;
}
else
{
fullDate = year + INSERT_HYPHEN + month + INSERT_HYPHEN + day;
}
return year + month + day;
}
/**
*
*/
public void setYear (int whatIsYear)
{
if ((whatIsYear >= 1990) && (whatIsYear <= 2013))
{
year = whatIsYear;
}
else
{
year = 2013;
}
}
/**
*
*/
public void setMonth (int whatIsMonth)
{
if ((whatIsMonth >= 1) && (whatIsMonth <= 12))
{
month = whatIsMonth;
}
else
{
month = 01;
}
}
/**
*
*/
public void setDay (int whatIsDay)
{
if ((whatIsDay >= 1) && (whatIsDay <= 31))
{
day = whatIsDay;
}
else
{
day = 01;
}
}
}
只是一些更多的背景。我正在構建的課程有三個字段,年份,月份和日期,年份可以在1900年到今年之間,包括1月和12月之間,可以在1到12之間,包括天數在內和1到31之間。使用符號con而不是代碼中的「魔術」數字,例如public static final int FIRST_MONTH = 1;
默認構造函數將year設置爲當前年份,將月份設置爲第一個月份,將日期設置爲第一天。非默認構造函數測試每個參數。如果year參數超出了可接受的範圍,它將該字段設置爲當前年份。如果月份參數超出了可接受的範圍,它會將字段設置爲第一個月份。如果day參數超出了可接受的範圍,它將字段設置爲第一天。
每個字段都有一個存取方法和一個增變方法。所有三種增變器方法都檢查其參數的有效性,如果無效,則以與非默認構造器相同的方式設置相應的字段。
這是我遇到麻煩的部分。我必須包含一個名爲「public String getFullDate()」的方法,它返回一個字符串,格式爲:YYYY-MM-DD,例如2012-01-01。帶有單個數字的月份和日期填充前導零。 「
任何幫助任何將不勝感激,即使只是一個想法:)謝謝。
使用單引號一個char''-''。零應該最好也是字符。 – 2013-02-11 11:56:30