我目前正在制作一个程序,我想输入“红色”或“黑色”,然后输入 1-10 中的一个数字。
输入应类似于 Red 7
或 Black 3
如果输入无效,我希望程序重新打印该行。我正在考虑使用 try { 然后 catch {。但我不确定要检查什么条件。
我试过这个:
System.out.print("Please choose Black or Red....and a number from 1-10 (Example : Black 4): ");
String color = input.next();
int number = input.nextInt();
if(!color.equals("Red") || !color.equals("red") || !color.equals("Black") || !color.equals("black")) {
System.out.println("Incorrect input. Please enter Black or Red: ");
color = input.next();
}
if(!(number < 0 || number > 10)) {
System.out.println("Incorrect input. Please re-enter a valid number from 1 to 10: ");
color = input.next();
}
有很多方法可以解决这种情况。我建议如下,它逐行读取输入:
- 使用
String#split(regex)
将输入分隔成一个数组.
- 使用
String#equalsIgnoreCase(String)
检查颜色输入.
- 使用
Integer#parseInt(String)
解析输入的数字.
- 使用
switch
检查输入的数字.
当所有的东西放在一起时,它看起来像这样:
System.out.println("Please choose Black or Red....and a number from 1-10: ");
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag) {
String line = input.nextLine();
String[] parts = line.trim().split("[\\s]");
try {
int num = Integer.parseInt(parts[1]);
if (parts[0].equalsIgnoreCase("red")) {
switch (num) {
case 1:
{
flag = false;
//...
}
/*
* I'm not going to include all the cases
*/
default:
throw new NumberFormatException();
}
} else if (parts[0].equalsIgnoreCase("black")) {
switch (num) {
case 1:
{
flag = false;
//...
}
/*
* I'm not going to include all the cases
*/
default:
throw new NumberFormatException();
}
} else {
System.out.println("'" + parts[0] + "' is invalid."
+ "\nPlease re-enter a color");
}
} catch (NumberFormatException e) {
System.out.println("'" + parts[1] + "' is invalid."
+ "\nPlease re-enter a number");
}
}
当然,有一种使用方法和事物的更简洁的方法,但为了清楚的答案,我不会包括它。