java - try block 内声明的变量无法解析

标签 java exception

刚刚学习异常捕获。这会产生“高度无法解析为变量”。我想我错过了一些重要的东西。

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/

相关文章:

c++ - 如何正确处理 header 中的异常?

java - 无法从下拉菜单中访问所选值

java - 修改 HazelcastHttpSession 实例的属性时是否需要锁定它?

java - 多次运行 Exception Handling Java 代码时的不同输出

php - 异常(exception)-用于用户通知还是错误记录?

c# - .NET - 实现 "catch all exceptions handler"的最佳方法是什么

java - 如何重写子类的equals方法

java - 如何使用 Maven 将 jar 部署到 S3?

java - 如何使用java将当前日期和时间保存到数据库?

python - 有没有一种方法可以在不使用 Python 中的 try/except 的情况下对引发到程序顶部的异常使用react?