初学者Java不需要构造函数上的参数错误 [英] Beginner Java required no arguments error on constructor

查看:54
本文介绍了初学者Java不需要构造函数上的参数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,作为一个类的作业,我试图制作一个简单的圆形类,然后将其用作构造函数。
这是我的课程代码:

So as an assignment for a class i'm trying to make a simple circle class and then use it as an constructor. Here is my class code:

public class Circle
{
  private double radius;
  private double pi;

  public void setRadius(double rad)
  {
    radius = rad;
  }

  public double getRadius()
  {
    return radius;
  }

  public double getArea()
  {
    return pi * radius * radius;
  }

  public double getDiameter()
  {
    return radius * 2;
  }

  public double getCircumference()
  {
    return 2 * pi * radius;
  }
}

这里是使用该类构造构造函数的程序:

Here's the program that uses the class to make a constructor:

import java.util.Scanner; //scanner class for input

  public class CircleDemo
{
  public static void main(String[]args)
  {
    double radiusIn; //gets radius from input

    Scanner keyboard=new Scanner(System.in); //activates scanner class in program

    System.out.print("Enter the radius of a circle: ");
    radiusIn=keyboard.nextDouble();

    Circle circularObject= new Circle(radiusIn);

    System.out.println("The circle's area is" + circularObject.getArea());
    System.out.println("The circle's diameter is" + circularObject.getDiameter());
    System.out.println("The circle's circumference is" + circularObject.getCircumference());
  }
}

,我得到错误:
Error :类Circle中的构造函数Circle不能应用于给定类型;
必需:无参数
:双
原因:实际参数和正式参数列表的长度不同

and i get the error: Error: constructor Circle in class Circle cannot be applied to given types; required: no arguments found: double reason: actual and formal argument lists differ in length

我什么都没看到我的代码有误,但随后我再次使用了老师给我们的示例。

I don't see anything wrong with my code, but then again i'm using the sample that my teacher gave us.

推荐答案

您正在调用构造函数这里

You are calling the constructor here

Circle circularObject= new Circle(radiusIn);

但是您的 Circle 类,该类与您要传入的参数匹配。返回您的 Circle 类,并定义一个构造函数,该构造函数使用 double 参数:

But there is no constructor defined in your Circle class which matches the argument you are passing in. Return to your Circle class and define the constructor which takes a double argument:

public Circle(double val)
{
    //Implementation
}

请注意,如果没有为类提供显式构造函数,Java会自动为您提供具有空实现,无参数的公共构造函数供您使用。一旦定义了第一个显式构造函数,该默认构造函数就消失了,这意味着您必须手动重新定义它。

Note that if you do not provide an explicit constructor for a class, Java will automatically provide you with an empty-implementation, no argument, public constructor for you to use. Once you define your first explicit constructor, that default constructor is gone, meaning you would have to re-define it manually.

这篇关于初学者Java不需要构造函数上的参数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆