【问题标题】:How do I use display method and call constructor?如何使用显示方法和调用构造函数?
【发布时间】:2014-12-08 16:42:10
【问题描述】:

我需要为 x 和 y 使用一个变量。我必须设置一个方法来获取 x,y。我必须使用一种方法来设置 x 和 y。我必须使用显示方法来显示 x 和 y 的点。然后使用接受用户输入并将它们设置为 x 和 y 的构造函数。最后创建一个创建 x 和 y 的 2 个实例的主类。我认为我的问题出现在我的显示方法上。我的程序编译/构建没有错误;但是没有任何显示或提示用户输入。在尝试调用 main 方法中的第一个类之前,我是否可能需要在第一个类中调用我的构造函数?

第一个文件:

public class Point2D extends JFrame
{
   Scanner input = new Scanner(System.in);
   private String x;
   private String y;


   public String getX()
   {
       return x;

   }
   public String getY()
   {
       return y;

   }

   public void setValue(String whatIsX, String whatIsY)
   {
      x = whatIsX;
      y = whatIsY;

   }

   public void display()
   {
      System.out.println(x);
      System.out.println(y);
   }

   public void Point2D()
   {
      System.out.println("Please enter value for X >>");
      input.nextLine();
      x = input.nextLine();
      System.out.println("Please enter value for Y >>");
      input.nextLine();
      y = input.nextLine();
   }

}

第二个文件:

public class MainPoint2D 
{
    public static void main(String[] args)
    {
       Point2D a = new Point2D();
       Point2D b = new Point2D();
    }
}

【问题讨论】:

  • 因为你从不调用display 方法,很明显。

标签: java constructor instance


【解决方案1】:

从“构造函数”中删除 void

 public Point2D()
 {
  System.out.println("Please enter value for X >>");
  input.nextLine();
  x = input.nextLine();
  System.out.println("Please enter value for Y >>");
  input.nextLine();
  y = input.nextLine();
 }

构造函数没有返回类型,编译器将其视为类方法。

另外,不要忘记在创建对象后调用任何要执行的方法:

   Point2D a = new Point2D();
   Point2D b = new Point2D();
   a.display();
   b.display();

【讨论】:

    【解决方案2】:

    删除public void Point2D()

    中的void

    【讨论】:

      【解决方案3】:

      public void Point2D() 定义了一个名为“Point2D”的方法,其返回类型为void,而不是构造函数。构造函数没有任何返回类型,甚至没有void。将其更改为public Point2D()

      目前,您的 main 方法正在调用默认的 Point2D 构造函数,该构造函数未定义,因此编译器为您提供了一个空的构造函数。

      【讨论】:

        【解决方案4】:

        我想你想改变这个

        public void Point2D()
           {
              System.out.println("Please enter value for X >>");
              input.nextLine();
              x = input.nextLine();
              System.out.println("Please enter value for Y >>");
              input.nextLine();
              y = input.nextLine();
           }
        

        到这里

        public Point2D()
           {
              System.out.println("Please enter value for X >>");
              input.nextLine();
              x = input.nextLine();
              System.out.println("Please enter value for Y >>");
              input.nextLine();
              y = input.nextLine();
           }
        

        【讨论】:

          猜你喜欢
          • 2019-08-23
          • 2013-01-02
          • 2014-02-17
          • 2015-10-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-10
          • 2018-08-20
          • 1970-01-01
          相关资源
          最近更新 更多