-3

コードがあり、エラーの場所を知りたいのですが、助けてください: スロー行にエラーが 1 つだけあります

public static void main(String[] args) {
    try {
        Scanner input = new Scanner (System.in);
        System.out.println("Enter the number ");
        int x1 = input.nextInt();
        int i;
        if (x1>=0&&x1<=100) {
            i= (int) Math.pow(x1,2);
            System.out.println("the squre of  "+ x1 + " is "+ i);
        }
        else 
            throw new MyException();   // what is the error here?
    } catch(MyException me) {
        System.out.println(me);
        String message = me.getMessage();
    }
}

public class MyException extends Exception {
 public String getMessage() {
        return " the number is out of ring";
    }
    }

}
4

2 に答える 2

0

It looks like you haven't quite posted your entire class, but based on the error message it looks like MyException occurs inside your class, something like:

public class TheClass {

    public static void main(String[] args) {
        ....
    }

    public class MyException extends Exception {
        ....
    }

}

This makes MyException an inner class. Every instance of MyException must therefore "belong" to an instance of TheClass. That's why you get the "non-static variable this" error message. When you say new MyException, you're inside the static main method, so it has no way of knowing what instance of TheClass the new MyException object will belong to.

I don't think you want this to be an inner class. Either move MyException outside of TheClass, or make it static:

public static class MyException extends Exception {

Making it static would make it a "nested" rather than an "inner" class, so that it doesn't belong to an instance of TheClass. You probably want to move it outside, though. I don't see a good reason for it to be in your other class.

于 2014-10-22T00:18:45.577 に答える
0

まず、getMessage メソッドは MyException クラスの外にあります。次に、getMessage() というメソッドを呼び出そうとしていますが、これはメイン メソッドでは実行できません。me.getMessage(); を呼び出す必要があります。

于 2014-10-22T00:01:27.143 に答える