2

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

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

2 回答 2

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 块内的高度您必须注意它仅在try块内有效。每当您外出时,您都无法访问它。 还有一点,永远不要忘记 catch 块中的消息,强烈建议有一个有意义的消息,如果没有,那就太好了。
printStackTrace()

于 2013-06-30T21:17:33.383 回答
1

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

于 2013-06-30T22:12:48.967 回答