【问题标题】:Java Objects and arraysJava 对象和数组
【发布时间】:2017-05-20 17:28:11
【问题描述】:

我对 java 比较陌生,我想知道如何编写这组代码。

目前我有一个类可以从用户输入的列表中为每个名称和数字对创建一个对象

public class Data
{
    private String x;
    private int y;

 //Constructor, getters and setter methods ...

根据用户输入创建了许多对象。然后应该将对象放入另一个包含对象数组的类文件中

public static void Input ()
{
    Scanner s = new Scanner (System.in);
    int listLength = 20;
    for (int i = 0 ; i < listLength; i++)
    {
        String userString = s.next();
        Int userInt = s.nextInt();
        Data d = new Data(userString, userInt);
        DataArray = //created objects need to be inputted to another class
     }

....

public class DataArray
{

    private Data[] arrayObjects; //unsure how to write the array
    private int count;

    public DataArray (Data inObject)
    {
         ....

然后我需要使用新构建的数组并将其作为列表显示给用户。我不确定如何从课堂上引用所述数组。从环顾四周,我遇到了许多其他人使用 ArrayList。我宁愿通过使用计数变量从数组中获得不同的元素。

【问题讨论】:

  • 由于ListArrayList 实现)包含.get(int index) 方法,因此您关于通过计数变量访问的声明对我来说真的没有意义。 List 方法的优点之一是避免分配数组大小,而且更容易迭代。

标签: java arrays class object


【解决方案1】:

一个数组对象已经提供了一个.length 属性,所以你的DataArray 类并没有真正增加使用简单数组的价值。

public static Data[] Input () {
    Scanner s = new Scanner (System.in);
    int listLength = 20;
    Data[] dataArray = new Data[listLength]; // Define here
    for (int i = 0 ; i < listLength; i++) {
        String userString = s.next();
        int userInt = s.nextInt();
        Data d = new Data(userString, userInt);
        dataArray[i]=d; // Assign here
    }
    . . .
    return dataArray;
}

【讨论】:

    【解决方案2】:
    public getData(){
      arrayObjects = new ArrayList<>();
      for(int i=0;i<arrayObjects.lenght;i++){
         System.out.println(arrayObjects.get(i).getX();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      相关资源
      最近更新 更多