你好,我正在一个项目上工作,我正试图找出我的代码有什么问题,以便它能正确打印。编写一个Java程序,提示用户生日的日期和月份(都是整数),然后打印相应的星座。
public class Birthday {
public static void main(String args [] ) {
String birthday = System.console().readline("Enter your birthday, month then day.");
float value = Float.parseFloat(birthday);
if (month < 1 || month > 12) {
System.out.println("Invalid month please try again.");
}
else if (day < 1 || day > 31) {
System.out.println("Invalid day please try again.");
}
else if (month = 1 || month = 12) {
}
else if (day >= 22 || day <= 19); {
System.out.println(birthday + "Capricorn");
}
}
}
这些是我得到的错误:
Birthday.java:3: readline(boolean) in java.io.Console cannot be applied to (java.lang.String)
float birthday = System.console().readline("Enter your birthday, month then day.");
^
Horoscopes.java:4: cannot find symbol
symbol : variable month
location: class Birthday
if (month < 1 || month > 12) {
^
Horoscopes.java:4: cannot find symbol
symbol : variable month
location: class Birthday
if (month < 1 || month > 12) {
^
Horoscopes.java:8: cannot find symbol
symbol : variable day
location: class Birthday
else if (day < 1 || day > 31) {
^
Horoscopes.java:8: cannot find symbol
symbol : variable day
location: class Birthday
else if (day < 1 || day > 31) {
^
Horoscopes.java:12: cannot find symbol
symbol : variable month
location: class Birthday
else if (month = 1 || month = 12) {
^
Horoscopes.java:12: cannot find symbol
symbol : variable month
location: class Birthday
else if (month = 1 || month = 12) {
^
Horoscopes.java:16: cannot find symbol
symbol : variable day
location: class Birthday
else if (day >= 22 || day <= 19); {
^
Horoscopes.java:16: cannot find symbol
symbol : variable day
location: class Birthday
else if (day >= 22 || day <= 19); {
^
9 errors
乍一看,您并没有定义month
是什么day
。
同样,你正在做的是Float.parseFloat(birthday)
,但所有这些将会给你一个float
,看起来像这样:
如果我输入20150713
,我将得到
float value = 20150713.00
这并没有把它们分成月和日。
我建议的是,而不是将String birthday
转换为浮点数,我会将其转换为日期结构。
一旦你有了一个日期结构,比如Date
或LocalDate
,你就可以比较month
和day
。
您可能希望这样做(只是部分,我不想破坏您的作业):
public static final void main(String args...) {
while(true) {
Scanner sc = new Scanner(System.in);
System.out.println("please enter the month in which you are born:");
int month = sc.nextInt();
System.out.println("please enter the day in which you are born:");
int day = sc.nextInt();
if (!checkMonth(month)) {
System.out.println("Invalid month please try again.");
continue;
} else if (!checkDay(day)) {
System.out.println("Invalid day please try again.");
continue;
} else {
// todo: work with valid birthday
}
}
}
public static boolean checkMonth(int month){
// todo: check if valid
return true;
}
public static boolean checkDay(int day){
// todo: check if valid
return true;
}