简体   繁体   中英

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

So I have 3 Parallel Arrays. I need a method that will allow for the user to add to these arrays. As well as another method to be able to identify a certain item and remove it. As well as another method to identify an item and edit/change the contents of that item in the array.

These are my 3 arrays...

I need to add the brand name of the computer to: String[] computerBrand

I need to add the processor speeds to: double[] computerSpeed

and I need to add the computers price to: double[] computerPrice

The first array (string) holds the brand name of computer. (Dell) the second array (double) holds the processor speed of the computer. (2.5) the third array (double) holds the price of the computer. (1500)

How do I take user input and put them in the array?

(I CANNOT USE ARRAYLISTS)

For taking input look at the Scanner class.

Scanner

For adding the values to your arrays just do this:

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

where these 3 values are the one read by the Scanner,
and i is some index/counter integer variable.

But first make sure you initialize your arrays eg:

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"
    );
}

By reading the code you can understand a simple thing: every array will share the same index.

For your real code, you just need to get name, price and speed of the pc and put everything in the arrays using the same index. If you use it in separate code you can store the last index and use it (more info depends on how it should work.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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