import javax.swing.JOptionPane;
public class Lab42{
public static void switchExample(){
String str1;
int s1, result;
do {
str1 = JOptionPane.showInputDialog("Enter the date: ");
s1 = Integer.parseInt(str1);
result = s1 % 7;
switch (result){
case 1:
System.out.printf("• %d falls on a Monday", s1); break;
case 2:
System.out.printf("\n• %d falls on a Tuesday", s1); break;
case 3:
System.out.printf("\n• %d falls on a Wednesday", s1); break;
case 4:
System.out.printf("\n• %d falls on a Thursday", s1); break;
case 5:
System.out.printf("\n• %d falls on a Friday", s1); break;
case 6:
System.out.printf("\n• %d falls on a Saturday", s1); break;
default:
System.out.printf("\n• %d falls on a Sunday", s1); break;
}
} while(s1 <= 31 && str1.compareTo("quit") != 0);
}
public static void main(String [] args){
switchExample();
}
}
output: Exception in thread "main" java.lang.NumberFormatException: For input string: "quit"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at Lab42.switchExample(Lab42.java:12)
at Lab42.main(Lab42.java:44)
我想在数字1-31之间接受用户的输入,并打印它所在的日子,(假设1号是在星期一),我想让循环继续下去,直到数字大于31或者用户的类型退出。谁能告诉我,我哪里做错了?
谢谢!(我是StackOverflow的新手,如果问题不符合模式请见谅)。
问题是 quit
不能转换为整数,因此,需要先检查输入的值,如果为 quit
. 如果输入不是 quit
,检查是否可以将其解析成一个 int
并在输入不能解析为整数时进行回环。
具体操作如下。
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String str1;
int s1 = 0, result;
boolean valid;
do {
do {
valid = true;
str1 = JOptionPane.showInputDialog("Enter the date: ");
if (str1.equalsIgnoreCase("quit")) {
break;
}
try {
s1 = Integer.parseInt(str1);
if (s1 > 31) {
break;
}
result = s1 % 7;
switch (result) {
case 1:
System.out.printf("• %d falls on a Monday", s1);
break;
case 2:
System.out.printf("\n• %d falls on a Tuesday", s1);
break;
case 3:
System.out.printf("\n• %d falls on a Wednesday", s1);
break;
case 4:
System.out.printf("\n• %d falls on a Thursday", s1);
break;
case 5:
System.out.printf("\n• %d falls on a Friday", s1);
break;
case 6:
System.out.printf("\n• %d falls on a Saturday", s1);
break;
default:
System.out.printf("\n• %d falls on a Sunday", s1);
break;
}
} catch (NumberFormatException e) {
System.out.println("Wrong input. Try again.");
valid = false;
}
} while (!valid);
} while (!str1.equalsIgnoreCase("quit"));
}
}