【问题标题】:Java - Add user input to 3 arrays? (Parallel Arrays)Java - 将用户输入添加到 3 个数组? (并行阵列)
【发布时间】:2014-02-01 22:57:28
【问题描述】:

所以我有 3 个并行阵列。我需要一种允许用户添加到这些数组的方法。以及另一种能够识别某个项目并将其删除的方法。以及另一种识别项目并编辑/更改数组中该项目内容的方法。

这是我的 3 个数组...

我需要将电脑的品牌名称添加到: String[] 计算机品牌

我需要将处理器速度添加到: double[] 计算机速度

我需要将计算机价格添加到: double[] 电脑价格

第一个数组(字符串)包含计算机的品牌名称。 (戴尔) 第二个数组(双)保存计算机的处理器速度。 (2.5) 第三个数组 (double) 保存计算机的价格。 (1500)

如何获取用户输入并将它们放入数组中?

(我不能使用数组列表)

【问题讨论】:

  • 为什么要使用并行数组?这正是你应该有一个类数组Computer的情况。
  • 这个问题是关于物体恐惧症而不是平行数组。
  • 教授要求我们在这个项目 O.o 中出于某些奇怪的原因使用并行数组
  • 大声笑为什么?这里的类比 3 个数组更有用也更直观。无论如何,它与使用一个数组相同,不同之处在于您将使用相同索引的 3 个数组。
  • 别问我。也许是因为我的教授在 30 年前学会了编码?大声笑谁知道。但它在说明中特别指出:“不要使用阵列!使用并行阵列!”而且我在网上的任何地方都找不到帮助,因为没有人使用并行数组!

标签: java arrays methods input


【解决方案1】:

要获取输入,请查看 Scanner 类。

Scanner

要将值添加到数组中,只需执行以下操作:

computerBrand[i] = <value_brand>;
computerSpeed[i] = <value_speed>;
computerPrice[i] = <value_price>;
i++;

其中这 3 个值是扫描仪读取的值,
i 是一些索引/计数器整数变量。

但首先要确保你初始化了你的数组,例如:

computerBrand = new String[100];
computerSpeed = new double[100];
computerPrice = new double[100];

【讨论】:

  • 好的,所以我把它添加到数组中,但它添加到数组的开头。有没有什么简单的方法可以让它添加到数组的末尾,以及当我退出我的程序时,它应该将数组整齐地保存回computers.txt 文件。但由于某种原因,它在保存和退出后搞砸了我的 .txt 文件中的行和内容的格式。
  • 我的伪代码添加到数组的末尾。 3 个数组共享一个公共索引/计数器变量,仅此而已。
  • 这是我的computer.txt在添加之前的样子然后保存+退出:hastebin.com/wajaholero.md,但之后看起来像这样:hastebin.com/qerubemumi
  • 啊,这是由于我的文件输出/保存和退出问题。让我尝试修复它。
  • 我在哪里声明 i 或 counter 变量?主要是?但是我不明白它怎么知道我的数组的末端在哪里。就像最后一个字符串或双精度或最后一行或其他什么。
【解决方案2】:
// Create the arrays
// (anyway It's better to use double for price and speed)
String[] computerBrand = new String[5];
String[] computerSpeed = new String[5];
String[] computerPrice = new String[5];

//
// Now you have 3 arrays which contains computer info

// A Computer with index 0 will contains his name in computerBrand[0], speed in computerSpeed[0] and price in computerPrice[0]

// Put info into the arrays, here is random in the real code you get the info from the user.. you can understand it's the same way you use for standard arrays (it's anyway arrays)
for (int i = 0; i < 5; ++i)
{
    computerBrand[i] = "Computer " + i;
    computerSpeed[i] = String.valueOf(Math.floor(Math.random()*10));
    computerPrice[i] = String.valueOf(Math.floor(Math.random()*500));
}

// print info
//
for (int i = 0; i < 5; ++i)
{
    // As you can see, i have used the same index in every array
    System.out.println(
            "Brand: " + computerBrand[i] +
            " Speed: " + computerSpeed[i] +
            " Price: " + computerPrice[i] + "E"
    );
}

通过阅读代码你可以理解一个简单的事情:每个数组都将共享相同的索引。

对于您的真实代码,您只需要获取 PC 的名称、价格和速度,然后使用相同的索引将所有内容放入数组中。如果您在单独的代码中使用它,您可以存储最后一个索引并使用它(更多信息取决于它应该如何工作。)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    相关资源
    最近更新 更多