2016-02-24 32 views
0
public class swap 
{ 
    public class Point 
    { 
     public int x=0; 
     public int y=0; 

     public Point(int a, int b) 
     { 
      this.x = a; 
      this.y = b; 
     } 

     public void swapxy(Point p) 
     { 
      int t; 

      t = p.x; 
      p.x = p.y; 
      p.y = t; 
     } 

     public String ToString() 
     { 
      return ("x="+x+" y="+y); 
     } 
    } 


    public static void main(String[] args) 
    { 
     Point pxy = Point(10,20); 

     pxy.swapxy(pxy); 
     System.out.println(pxy); 

    } 

} 

我得到的方法是undefined錯誤Point pxy = Point(10,20);什麼是錯的?使用構造函數智能在Java中的新對象

+0

請重新格式化您的代碼。把它複製到一個編輯器中按TAB鍵縮進一次,並將代碼複製回問題中。 –

+0

你有任何C背景嗎? –

回答

3

你已經忘記了new關鍵字:

Point pxy = new Point(10,20); 
      ↑↑↑ 
+0

我添加了「新」但stiil我收到錯誤:沒有封閉類型交換的實例是可訪問的。必須使用封閉的類型交換實例來限定分配(例如,x.new A(),其中x是交換實例)。 – user3879626

1

正確的做法:Point pxy = new Point(10,20);

1

要創建一個實例,使用new關鍵字

3

你忘了後寫入新「=」;

正確的方法是這樣的:

Point pxy = new Point(10,20); 

呵呵,關鍵是你要使用的類是交換的內部類,所以在使用前必須將它實例。

如果你不需要這是一個內部類,聲明這個類在單獨的文件,或者你可以做波紋管代碼:

public class Swap { 
     //add static in the class to access it in a static way 
     public static class Point 
     { 
//change the attributes to private, this is a good practice 
      private int x=0; 
      private int y=0; 

      public Point(int a, int b) 
      { 
       this.x = a; 
       this.y = b; 
      } 

      public void swapxy(Point p) 
      { 
       int t; 

       t = p.x; 
       p.x = p.y; 
       p.y = t; 
      } 

      public String ToString() 
      { 
       return ("x="+x+" y="+y); 
      } 
     } 

     public static void main(String[] args){ 

       Swap.Point pxy = new Swap.Point(10,20); 
       System.out.println(pxy.ToString()); 
     } 

    } 
+0

我添加了新的但stiil我收到錯誤:沒有封閉類型交換的實例是可訪問的。必須使用封閉的類型交換實例來限定分配(例如,x.new A(),其中x是交換實例)。 – user3879626

+0

我編輯了答案,看一看。 –