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

ブロックの外側で見えるように、変数 'height' を try ブロックの外側で宣言します。

于 2013-06-30T22:12:48.967 に答える
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 ブロック内でのみ有効であることに注意する必要あります。外に出たらいつでもアクセスできません。 もう 1 つは、catch ブロック内のメッセージを決して忘れないでください。意味のあるメッセージを含めることを強くお勧めします。
printStackTrace()

于 2013-06-30T21:17:33.383 に答える