【问题标题】:java constructor error (cannot pass int to the constructor)java构造函数错误(不能将int传递给构造函数)
【发布时间】:2013-04-23 05:05:45
【问题描述】:

嗨,我是 java 新手,我一直在尝试将 int 形式的 main 方法传递给另一个类中的构造函数,但是发生了某种错误。我不明白我做错了什么。

带有main方法的类:

import java.util.Scanner;

public class _01 {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your : ");
        String name = input.nextLine();
        int size = name.length();

        //System.out.println(size);


        _02 process = new _02(size);

    }

}

具有构造函数的类:

public class _02 {

    int maxsize;
    int top;
    String arrayStack[];

    public void _02(int size) {

        maxsize = size;
        arrayStack = new String[maxsize];
        top = -1;
    }

    public void push(String... letters) {

        arrayStack[++top] = letters;

    }

    public String pop() {

        return arrayStack[top--];


    }
}

我收到的错误消息:

线程“主”java.lang.Error 中的异常:未解决的编译 问题:构造函数_02(int)未定义

在_01.main(_01.java:16)

【问题讨论】:

  • 看来今天每个人都在忙着... ;-) 4 个答案并在一分钟内发表评论。

标签: java methods constructor integer stack


【解决方案1】:

那是因为您使用的是void。 Java 认为这些是方法,而不是构造函数。首先停止给你的班级起可怕的名字。然后这样做:

public class Whatever {
   private Integer size;
   public Whatever(Integer size) {
      this.size = size;
      System.out.println("I am a constructor");
   };
};

示例

public class Article {
    private String title;
    private String content;
    private String author;
    private DateTime publishDate;

    public Article(String title, String content, String author, DateTime publishDate) {
        this.title = title;
        this.content = content;
        this.author = author;
        this.publishDate = publishDate;
    };

};

假设我们正在合作开展一个报纸项目。如果我阅读您的代码并看到_01,那对我来说毫无意义。相反,如果我看到Article、title、content 等。我可以立即理解您写的内容并随意使用。

如果两周后您回到自己的代码,您将不知道_01 的含义。和许多开发人员一样,您不会记得。甚至有一个关于它的笑话,通过评论完成。它是这样的:

/**
 * At the time of this writing, only God and I knew what I was doing.
 * Now, only God knows.
 * /

请记住,代码很容易编写,但很难阅读。

【讨论】:

  • 谢谢你!我必须这样命名课程,因为我的老师希望我们遵循相同的格式:/
  • 你能举个例子吗?
【解决方案2】:

构造函数是没有返回类型的方法,所以你的构造函数声明应该是:

public _02(int size)

一个好的做法是遵循 java 风格指南,使用带有大写字母的名称作为类名,例如 Two

【讨论】:

    【解决方案3】:

    构造函数没有返回类型。因此,如果您想将 void 用作构造函数,请从 public void _02(int size) 中删除它。

    不过你的班级命名有点奇怪......

    【讨论】:

      【解决方案4】:

      从 public void _02(int size) { ... }

      中删除“void”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 2022-01-12
        • 1970-01-01
        • 2014-03-07
        • 2011-09-24
        • 2012-01-15
        相关资源
        最近更新 更多