刚刚学习异常捕获。这会产生“高度无法解析为变量”。我想我错过了一些重要的东西。
import java.util.*;
public class Step4_lab01
{
public static void main(String[] args)
{
Scanner userIn = new Scanner(System.in);
System.out.print("Input height: ");
try {
int height = userIn.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("ERORRORrr");
}
System.out.print("Input width: ");
int width = userIn.nextInt();
Rectangle rektangel1 = new Rectangle(height,width);
rektangel1.computeArea();
}
}
最佳答案
我认为你最好将代码更改为:
int height = 0;
int width = 0;
Scanner scanner = new Scanner(System.in);
while(true){
try{
height = scanner.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("Height must be in numeric, try again!");
scanner.next();
/*
* nextInt() read an integer then goes to next line,what if the input was not
* numeric, then it goes to catch, after catch it goes back to try, then reads
* an empty line which is also not numeric, that caused the infinity loop.
* next() will read this empty line first, then nextInt() reads the integer value.
* The problem have been solved.
/*
}
}
对宽度也执行此操作,您在代码中没有想到的是 try block 内的高度,您必须注意它仅在内部有效 try block 。每当你外出时,你都无法访问它。
另一件事,永远不要忘记catch block 中的消息,强烈建议有一个有意义的消息,如果没有,那么printStackTrace()
会很棒。
关于java - try block 内声明的变量无法解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17394766/