我无法得到这些来编译它似乎是我试图传递布尔值的地方。第一个有2个错误对我没有任何意义
public class Date {
public int m;
public int d;
public int y;
boolean isLeapYear;
public String monthIs(){
return month;
m = Integer.parseInt(month);
}
public String dayIs(){
return day;
d = Integer.parseInt(day);
}
public Date(String year){
y = Integer.parseInt(year);
// Is y Divisible by 4
if (y % 4 == 0){
// Is y Divisible by 4 but not 100
if (y % 100 != 0)
isLeapYear = true;
// Is y Divisible by 4 and 100 and 400
else if (y % 400 == 0)
isLeapYear = true;
// It's Divisible by 4 and 100 but not 400
else
isLeapYear = false;
}
// It's not divisible by 4
else
{
isLeapYear = false;
public boolean getisLeapYear()
{
return isLeapYear;
}
}
}
}
DateJDialog类:
import javax.swing.JOptionPane;
/** This program runs the Date class to determine if
* the date entered falls within a leap year.
*/
public class DateJDialog
{
public static void main(String[] args)
{
String month;
String day;
String year;
boolean isitLeapYear;
Date date;
//Get Input
JOptionPane.showMessageDialog(null, "This program determines if the date
entered falls within a leap year.");
month = JOptionPane.showInputDialog("What month?");
day = JOptionPane.showInputDialog("What day?");
year = JOptionPane.showInputDialog("What year?");
//Create Date object
date = new Date(year);
if (date.getisLeapYear()==true);
if (isLeapYear = true)
JOptionPane.showMessageDialog(null, month + "-" + day + "-" + year
+ " does fall within a leap year.");
else
JOptionPane.showMessageDialog(null, month + "-" + day + "-" + year
+ " does not fall within a leap year.");
System.exit(0);
}
}
答案 0 :(得分:1)
您的代码中有一些错误,我会尽力指出它们。
首先,您有if-statement
:
if (date.getisLeapYear()==true);
if-statement
必须有一个由左大括号和右大括号组成的主体(我相信这会编译,但没有用处)。代替:
if (date.getisLeapYear()==true) {
//do something
}
由于这似乎是boolean
getter,因此条件检查可以缩短为:
if (date.getisLeapYear()) {//this checks for a "true" value, !date.getisLeapYear() checks for false
//do something
}
您对isLeapYear
为真的检查不正确,并在没有必要时再次输入。
if (isLeapYear = true)
应该是:
if (isLeapYear)//again checking if true. !isLeapYear would be checking for false.
您的构造函数构建奇怪且完全错误。首先,如果您使用if-else
语句,必须使用大括号。
以下是有效的,但被认为是不好的做法:
if (condition)
//do soemthing
以下需要大括号:
if (condition) {
} else if (another condition) {
} (...)
最后,您在构造函数中声明了一个getter。方法只能在类范围创建,这意味着无法在方法内创建方法。要解决这个问题:
public Date() {
(...)
}
public boolean getisLeapYear() {
return isLeapYear;
}
此外,就像提示一样,您可以在一个声明中链接变量的多个实例:
String month;
String day;
String year;
可以写成:
String month, day, year;
我不知道这是否涵盖了您的所有错误,但这是一个健康的开始。