如何修复代码? [关闭]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何修复代码? [关闭]相关的知识,希望对你有一定的参考价值。
你好我正在研究一个项目,我正在试图找出我的代码有什么问题,以便它能正确打印。编写一个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;
}
以上是关于如何修复代码? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章