在try块内声明的变量无法解析

时间:2013-06-30 20:54:41

标签: java exception-handling

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

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();
    }
}

2 个答案:

答案 0 :(得分:1)

我认为您最好将代码更改为:

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块中的 height ,你必须注意它只是在 vailed 里面尝试块。无论何时出门,您都无法访问它。
另一件事,不要忘记catch块内的消息,强烈建议有一条有意义的消息,如果没有,那么printStackTrace()就会很棒。

答案 1 :(得分:1)

在try块外面声明变量'height',以便在块外可见。