【问题标题】:Java - Make my unfilled arrays not print out null and 0?Java - 让我未填充的数组不打印出 null 和 0?
【发布时间】:2014-02-01 23:47:42
【问题描述】:

所以我必须使用 3 个并行数组。 (没有数组列表)

    String fileName = "computers.txt"; //file that lists computers       
    String[] computerBrand = new String[15]; //computer brand array      
    double[] computerSpeed = new double[15]; //computers processor speed array       
    double[] computerPrice = new double[15]; //computers price array

我让用户能够将计算机添加到阵列、编辑计算机以及从阵列中删除计算机。然后在程序结束时,当他们决定退出时,它会将数组保存回computer.txt 并关闭。

我的问题:

1.) 我的数组大小设置为 15,但在computers.txt 中只有 10 台计算机(为添加更多计算机提供空间)所以当我将数组打印到控制台时,它会打印出计算机品牌、速度和价格,但它还会打印最后 5 个品牌的 null、null、null,以及最后 5 个速度和价格的零。我该如何解决这个问题?

2.) 使用并行阵列(无阵列列表)如何确保如果用户将 6 或 7 台计算机添加到列表中,阵列可以随之扩展?有关说明的一些信息:“由于数组中的项目数可能会在整个程序执行过程中发生变化,因此您需要为数组中的项目数保留一个额外的整数变量。”

感谢您的帮助。

【问题讨论】:

  • 数组的索引是否与一台计算机匹配?你不应该有一个Computer 类吗?

标签: java arrays input parallel-processing output


【解决方案1】:

1) 循环并自己打印。打印从索引 0 到索引 N-1 的所有元素,
其中N 是i 的最后/当前值。这里i 是......在这里查看我之前的答案:
Java - Add user input to 3 arrays? (Parallel Arrays)

2) 在尝试添加新元素之前,请先检查 i == computerBrand.length
是真的。如果是这样,您需要扩展 3 个数组。所以重新创建 3 个数组但增加
它们的大小是 10。

String[] computerBrandExtended = new String[computerBrand.length + 10];
loop and copy all values from computerBrand to computerBrandExtended;
computerBrand = computerBrandExtended;

对所有 3 个数组执行此操作。现在你又有了一些空间。

【讨论】:

    【解决方案2】:

    创建适合您问题的 ArrayList

    这是arrayList的javadoc

    http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
    

    他们致力于动态内存分配,与他们一起工作非常容易,就像添加删除一样

    【讨论】:

    • OP 表示他们不想或不能在他们的解决方案中使用 ArrayLists。
    【解决方案3】:

    创建这样的东西:

    class Computer {
        String brabd;
        double price;
        double speed;
    }
    

    然后使用计算机集合:

    List<Computer> computers = new ArrayList<>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      相关资源
      最近更新 更多