-1

hi I'm new to java and I've been trying to pass an int form main method to a constructor in another class but there is some kind of error occurring. I can't understand what i did wrong.

class with the main method :

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);

    }

}

class that has the constructor:

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--];


    }
}

error message i'm getting :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor _02(int) is undefined

at _01.main(_01.java:16)

4

4 回答 4

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.
 * /

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

于 2013-04-29T13:45:22.920 回答
1

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

public _02(int size)

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

于 2013-04-29T13:46:36.847 回答
0

构造函数没有返回类型。因此voidpublic void _02(int size)如果您想将其用作构造函数,请移除。

你的班级命名虽然有点奇怪......

于 2013-04-29T13:44:59.860 回答
0

从 public void _02(int size) { ... } 中删除“void”

于 2013-04-29T13:45:09.543 回答