2016-09-15 118 views
-6

我想创建一个对象,我不确定我是否正在创建并且它是正确的。我的例子,可以说我有2个类(Userinput和paper).0fcourse存在和主。在这个例子中没有继承(只有2个简单的类)。我创建一个对象的权利?我怎么把它放在一个数组或相同的数组?创建一个对象并放入一个数组

package exercise; 
public class Exercise{ 
    static int N; //from keyboard .I have a class userinput.It doesnt need to write it here ,i have in the other class the problem 

    public static void main(String[] args) { // main class 

     Paper[] pin = new Paper[N]; //i create an array 
     Paper.setpencil(3); // i wrote the 3 .In this way i create 3 pencil? 
     Paper.getpencil(3); 

     Paper.setsomething(4); // i wrote the 4 .I create 4 ? 
     Paper.getsomething(4); 

    } } 
public class Paper{ //in this class i am confused 
    public Paper(){} //default constructor 

    private int pencil; 
    private String something; 

    public int getpencil(){ 
     return pencil; 
    } 
    public void setpencil(){ 
     pencil=UserInput.getInteger(): 
    } 
    public int getsomething(){ 
     return something; 
    } 
    public void setsomething(){ 
     something=UserInput.setInteger(); 
    } 
} 
+0

让您的代码可编译是该过程的第一步。其实这个代码不会编译,原因很多。 –

+5

请提供[mcve],格式正确。你现在显示的代码不应该编译,因为'setpencil'等是* instance *方法,但是你在'Paper'类型上调用它们就好像它们是静态方法一样。另外你的“Paper”的构造函数被称为'paper',所以它也不能编译,这部分没有任何与数组有关的问题,我建议一次处理一件事情 –

+0

可能的重复我可以添加新的项目到字符串数组?](http://stackoverflow.com/questions/14518195/how-can-i-add-new-item-to-the-string-array),只需在此输入差异case – px06

回答

2

有这样的说法:

Paper[] pin = new Paper[N]; 

创建类纸的对象的数组。

您还必须创建一个对象,像每个数组元素:

for (int i=0; i < N, i++) 
{ 
    pin[i] = new Paper(); 
} 

而接下来,你应该是指元件(例如,第一元素与索引0)这样的数组:

pin[0].setpencil(3);