所以它看起来它允许我输入所有的整数,当我做一个字符串或其他任何东西它确实给我错误,但我怎么去做它所以它只有1和/或2接受和3, 4,5 ....(其他每个号码)都不排除...... 代码
public static void main(String[] args){
System.out.println("Please enter 1 to add or 2 to multiply. "); // ask user to input 1 or 2
Scanner in = new Scanner(System.in);
try {
int add = in.nextInt(); // add for 1
int multiply = in.nextInt(); // multiply for 2
}
catch (Exception e) {
System.out.println("Operation failed. You need to enter 1 or 2.");
}
}
答案 0 :(得分:2)
这里的例外情况将是矫枉过正的IMO。只使用if else子句同样可以正常工作。像这样:
if(input == 1) {
// add
}
else if(input == 2) {
// multiply
}
else {
System.out.println("Operation failed. You need to enter 1 or 2.");
}
此外,如果您希望程序继续提示您可以将其包装在循环中。这是一个使用布尔标记来保持循环的小例子。这是实现此任务的众多方法之一。
public static void main(String[] args) {
System.out.println("Please enter 1 to add or 2 to multiply. "); // ask user to input 1 or 2
Scanner in = new Scanner(System.in);
boolean inputNotValid = true;
while(inputNotValid){
int input = in.nextInt();
if(input == 1) {
inputNotValid = false;
//add
System.out.println("adding");
}
else if(input == 2) {
inputNotValid = false;
//multiply
System.out.println("multiplying");
}
else {
System.out.println("Operation failed. You need to enter 1 or 2. Try again");
}
}
}
答案 1 :(得分:1)
替换:
int add = in.nextInt(); // add for 1
int multiply = in.nextInt(); // multiply for 2
使用:
int value = in.nextInt();
if(value == 1) // do add
if(value == 2) // do multiply
// else case = error
整个计划将成为:
public static void main(String[] args)
{
System.out.println("Please enter 1 to add or 2 to multiply. ");
Scanner in = new Scanner(System.in);
try
{
int value = in.nextInt();
if (value == 1)
{
System.out.println("add");
// do add
}
else if (value == 2)
{
System.out.println("mult");
// do multiply
}
else
{
// error
System.out.println("Operation failed. You need to enter 1 or 2.");
}
}
catch (Exception e)
{
System.out.println("Read operation failed. This should not happen!");
}
}
nextInt()的javadoc说:
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
你仍然可以捕获InputMismatchException,NoSuchElementException和IllegalStateException,因为in.nextInt()可以抛出它们。您也可以捕获异常(所有三个异常中唯一的超类)。 由于Exception是未经检查的Exception,您还可以删除try-catch。请注意,输入中的错误将退出整个程序。