2013-04-29 76 views
-1

嗨我是新来的java和我一直试图传递一个int形式的主要方法到另一个类的构造函数,但有一些错误发生。我不明白我做错了什么。java构造函数错误(不能通过int到构造函数)

类的主要方法:

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


    } 
} 

错误消息我得到:

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

at _01.main(_01.java:16)

+0

而且看起来大家今天都在...... ;-) 4个答案和一分钟内的评论。 – rolfl 2013-04-29 13:46:09

回答

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

Remeber,代码很容易写,但非常难读。

+0

谢谢你!我必须以这种方式命名课程,因为我的老师希望我们遵循相同的格式:/ – 2013-04-29 13:48:08

+0

你能举个例子吗? – 2013-04-29 13:51:29

+0

非常感谢。你真的很有帮助。 – 2013-04-29 13:59:12

0

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

你的类的命名是有点奇怪,但...

0

拆除公共无效_02(INT大小){...}

1

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

public _02(int size) 

一个很好的做法将是使用遵循Java的风格指南,使用名称以大写letrer作为类名称,示例Two