簡體   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