2016-01-21 39 views
0

幫助請.... 我是Java新手。我正在嘗試在Eclipse(Luna)的公共類「PeterAndSnowBlower」中編寫一個包含類「點」的代碼。 我也嘗試通過在類「point」中公開變量x,y並給出相同的錯誤。 我也用this.x和this.y代替x和y的構造函數裏面構造函數沒有在eclipse中的java中定義,雖然它被定義爲

這裏是我的代碼:

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

    } 
} 

的錯誤是:

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 
+1

不是按類別創建類。特別是如果你是新手,開始沒有IDE來學習基礎知識。 – Stultuske

+2

如果你想要一個靜態訪問,使你的''''類'靜態' –

回答

1

除非內類定義爲static,您不能從外部類的靜態方法實例化它。 non-static類需要this參考外部類。

將此類聲明爲static是有意義的。顯然它並不是指外部的階級。

+0

應該使用'靜態類點'? –

+0

謝謝@ kvr000,它正在工作。 –

1

你正在靜態訪問你的內部類(也就是說你不要從外部類的實例中去做)。

你需要的是一個static內部類,它在這裏非常有意義,因爲內部類不涉及外部類。

更改聲明

static class point { 
+0

感謝您的回覆。 –

相關問題