2016-02-24 35 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

我编辑了答案,看一看。 –