1

Help Please.... I am new in Java. I am trying to write a code that contains a class "point" into a public class "PeterAndSnowBlower" in Eclipse(Luna). I have also tried by making the variables x, y public in the class "point" and it gives the same error. I have also used this.x and this.y instead of x and y inside the constructors

Here is my code:

import java.util.*;
public class PeterAndSnowBlower {
    class point{
        int x;
        int y;
        public point() {
            x = y = 0;
        }
        public point(int a, int b){
            x = a;
            y = b;
        }
        public point(point p) {
            x = p.x;
            y = p.y;
        }
        public double distance(point P){
            int dx = x - P.x;
            int dy = y - P.y;
            return Math.sqrt(dx*dx + dy*dy);
        }
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n, x, y;
        point P = new point(0, 0);
        n = in.nextInt();
        P.x = in.nextInt();
        P.y = in.nextInt();
        Vector<point>points = new Vector<point>();
        for(int i = 0; i < n; i++){
            x = in.nextInt();
            y = in.nextInt();
            points.add(new point(x, y));
        }
        double r1, r2;
        r1 = r2 = P.distance(points.get(0));
        for(point point:points){
            r1 = Math.max(r1, P.distance(point));
        }

    }
}

the error is:

Multiple markers at this line
- No enclosing instance of type PeterAndSnowBlower is accessible. Must qualify the allocation with an enclosing instance of type PeterAndSnowBlower (e.g. 
 x.new A() where x is an instance of PeterAndSnowBlower).
- The constructor PeterAndSnowBlower.point(int, int) is undefined
NAbdulla
  • 85
  • 7

2 Answers2

1

Unless the inner class is defined static, you cannot instantiate it from static method from outer class. The non-static class requires this reference to outer class.

Here it makes sense to declare this class as static. Obviously it doesn't refer to outer class.

nitind
  • 19,089
  • 4
  • 34
  • 43
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
1

You're statically accessing your inner class (meaning you don't do it from an instance of the outer class).

What you need is a static inner class, which makes perfect sense here as the inner class doesn't refer to the outer one.

Change the declaration to

static class point {
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758