我被要求编写一些基于某些指令的程序(类)。我觉得我几乎崩溃了,但我正在做一些愚蠢的事情。我无法弄清楚如何将一个连字符添加到符号常量中,以便当我输入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