gpt4 book ai didi

java - 为什么这个程序不起作用

转载 作者:行者123 更新时间:2023-12-01 07:33:51 25 4
gpt4 key购买 nike

我被要求根据某些指令编写一个程序(类)。我觉得我快要明白了,但我正在做一些愚蠢的事情。我不知道如何将连字符添加到符号常量中,以便当我输入 INSERT_HYPHEN 时,它将在访问器方法中插入一个“-”。它说不兼容的类型>:( 另外,当我尝试将局部变量“fullDate”插入“getFullDate”访问器方法,然后输入“fullDate = 年+月+日”时,它指示“不兼容的类型!也许是因为accesor 方法是一个字符串,我试图在其中添加“ints”。我找不到解决方法。这是我的代码。

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 到 31 之间(含 1 和 31)。我必须在代码中使用符号常量而不是“魔术”数字,例如公共(public)静态最终 int FIRST_MONTH = 1;

默认构造函数将年设置为当前年份,将月设置为第一个月,将日设置为第一天。非默认构造函数测试每个参数。如果年份参数超出可接受的范围,则会将该字段设置为当前年份。如果月份参数超出可接受的范围,则会将该字段设置为第一个月。如果日期参数超出可接受的范围,则将该字段设置为第一天。

每个字段都有一个访问器方法和一个修改器方法。所有三个变元方法都会检查其参数的有效性,如果无效,则以与非默认值相同的方式设置相应字段构造函数。

这是我遇到问题的部分。我必须包含一个名为“public String getFullDate() 的方法,该方法返回一个具有以下格式的日期的字符串:YYYY-MM-DD,例如 2012-01-01。单个数字的月份和日期用前导零填充。 ”

任何帮助都将不胜感激,即使只是一个想法:)谢谢。

最佳答案

您应该使用单引号:

public static final char INSET_HYPHEN = '-';  

关于java - 为什么这个程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14811273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com