繁体   English   中英

Java-将用户输入添加到3个数组? (并行阵列)

[英]Java - Add user input to 3 arrays? (Parallel Arrays)

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

这是我的3个数组...

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

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

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

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

如何接收用户输入并将其放入数组中?

(我不能使用列表)

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

扫描器

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

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

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

但首先请确保初始化数组,例如:

computerBrand = new String[100];
computerSpeed = new double[100];
computerPrice = new double[100];
// 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的名称,价格和速度,然后使用相同的索引将所有内容放入数组即可。 如果在单独的代码中使用它,则可以存储最后一个索引并使用它(更多信息取决于它的工作方式。)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM