【发布时间】:2015-10-10 18:21:50
【问题描述】:
您好,我正在尝试编写一个代码,其输出类似于
Enter time in 24-hour notation:
13:07
That is the same as
1:07 PM
Again? (y/n)
y
Enter time in 24-hour notation:
10:15
That is the same as
10:15 AM
Again? (y/n)
y
Enter time in 24-hour notation:
10:65
There is no such time as 10:65
Try Again:
Enter time in 24-hour notation:
16:05
That is the same as
4:05 PM
Again? (y/n)
n
End of program
但我最终犯了一些错误,我无法弄清楚。
public class prp {
public static void main(String[] args) {
while (true) //add the remaining logic
{
System.out.println("Enter time in 24-hour notation HH:MM");
Scanner x = new Scanner(System.in);
String newhr = x.nextLine();
String hr[] = newhr.split(":");
int hours = Integer.parseInt(hr[0]);//HH
int minutes = Integer.parseInt(hr[1]);//MM
if ((hours >= 00 && hours <= 24) && (minutes >= 00 && minutes <= 59)) {
System.out.println("That is the same as: ");
if (hours <= 12) {
System.out.println(hours + ":" + minutes + " AM");
//System.exit(0);
} else if (hours > 12 && hours < 24) {
int hoursnew = hours - 12;
System.out.println(hoursnew + ":" + minutes + " PM");
//System.exit(0);
}
} else {
System.out.println("There is no such time as " + hours + " : " + minutes);
System.out.println("Try Again!");
//continue;
}
System.out.println("Again? [y/n]");
Scanner y = new Scanner(System.in);
String newyn = y.nextLine();
if (newyn == "y" || newyn == "n") {
if (newyn == "y") {
continue;
} else {
System.out.println("End of program");
System.exit(0);
//break;
}
}//end of while
}
}
}
程序在输入非整数时显示错误。此外,它没有破裂。如果用户输入非法时间,如 10:65 或 ab:cd,我想创建另一个名为 TimeFormatException 的异常类。
【问题讨论】:
-
好的,但是你的问题是什么?
-
当我输入字符“n”时应该退出循环
-
stackoverflow.com/questions/2912817/… 检查此链接仅将 int 作为输入。
标签: java loops exception-handling break continue