我需要为 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();
}
}
最佳答案
从您的“构造函数”中删除 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();
关于java - 如何使用显示方法和调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27362654/