【问题标题】:How do I create a new array object in Java? [duplicate]如何在 Java 中创建一个新的数组对象? [复制]
【发布时间】:2017-10-24 18:18:42
【问题描述】:

数组是用计数器声明的。每次将对象添加到数组中时,都需要使用计数器。

// declare Parcel array and parcel count variable
   private static Parcel[] parcels = new Parcel[10];
   private static int parcelCount = 0;

扫描仪中的信息需要创建一个新的 Parcel 对象并将其存储在数组 parcels 中的下一个可用(空)点中。

这就是我得到的。它似乎不起作用。我做错了什么?

System.out.print("Enter Parcel Number: ");
String parcelNumber = sc.nextLine();

String [] parcels = new String[0];

parcelCount ++;


System.out.print("Enter Sender Name: ");
String senderName = sc.nextLine();

String [] parcels = new String[1];

parcelCount ++;

System.out.print("Enter Return Address: ");
String returnAddress = sc.nextLine();

String [] parcels = new String[2];

parcelCount ++;

System.out.print("Enter Recipient Name: ");
String recipientName = sc.nextLine();

String [] parcels = new String[3];

parcelCount ++;

System.out.print("Enter Delivery Address: ");
String deliveryAddress = sc.nextLine();

String [] parcels = new String[4];

parcelCount ++;

【问题讨论】:

  • 您是否考虑阅读有关数组如何工作的教程:docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
  • 所以...在向我们展示一段代码,您在其中创建了相当多的新对象时,您希望我们告诉您如何做到这一点?
  • 你为什么要重新创建parcels?你为什么不在最后创建它?姓名和地址与包裹数量有什么关系?
  • Parcels 是字符串的数组对象。为什么要再次使用它?除非您要将它们放在不同的方法中。
  • parcelCount 变量不仅有助于跟踪当前存储在数组中的包裹数量,还用于帮助确定数组中下一个可用(空)点的位置。跨度>

标签: java arrays


【解决方案1】:

也许你需要https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html :)

或者使用类似的东西:

class ParcelHelper {
    static long count = 0;
    static Parcel[] parcels = new Parcel[10]

    public static void addParcels(Parcel parcel) {
        parcels[count] = parcel;
        count ++;
    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2010-11-02
    • 1970-01-01
    • 2017-02-02
    相关资源
    最近更新 更多