【问题标题】:Create an object and put in an array创建一个对象并放入一个数组
【发布时间】:2016-09-15 09:58:19
【问题描述】:

我只想创建一个对象,我不确定我是否正在创建并且它是正确的。我的例子,假设我有 2 个类(用户输入和纸张)。0当然有和主要的。在这个例子中没有继承(只有 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();
    }
}  

【问题讨论】:

  • 让您的代码可编译是该过程的第一步。实际上这段代码由于很多原因无法编译。
  • 请提供格式正确的minimal reproducible example。您目前显示的代码不应编译,因为 setpencil 等是 instance 方法,但您在 Paper 类型上调用它们,就好像它们是静态方法一样。此外,您的“Paper 的构造函数称为paper,因此也无法编译。该部分与数组无关。我建议一次处理一件事。
  • How can I add new item to the String array? 可能重复,在这种情况下只需键入差异
  • 你的代码有很多问题,包括编译时错误,我建议使用像Eclipse这样的IDE,它会对你有很大帮助。
  • 如果您要求人们尝试阅读,请正确缩进您的代码。

标签: java


【解决方案1】:

用这个声明:

Paper[] pin = new Paper[N];

你创建了一个 Paper 类的对象数组。

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

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

接下来你应该以这种方式引用数组的一个元素(例如索引为 0 的第一个元素):

pin[0].setpencil(3);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    相关资源
    最近更新 更多