[英](Java) How to Overwrite A 2D Array Where I've Already Declared Null Values
您好我正在使用二維數組來模擬自動售貨機。
我想聲明一個具有設定長度的數組並使其超大,以便它可以容納我向其中添加項目。
前任:
String[][] itemsT1 = new String[][] {null, null, null, null, null, null, null, null, null};
int itemCount = 0;
// The way I've been adding things in my "addItem' method is:
if ( (items.length > 0) && (itemsCount < items.length) ) {
items[itemsCount][0] = nameOfItem;
items[itemsCount][1] = expirationDate;
itemsCount++;
System.out.println("Item added");
}
// so that the end result of the array should be (with nameOfItem = "Water" and expDate = "15") something like this:
{ {"Water", "15"}, null, null, null, null, null, null, null, null}
// and it's scalable to be hypothetically used again:
{ {"Water", "15"}, {"Chocolate", "20"}, {"Juice", "25"}, null, null, null, null, null, null}
我可能會帶着更多問題回來,所以謝謝你的回答,如果我需要提供更多,請告訴我!
聲明您的 2D 字符串數組並初始化您要在自動售貨機中處理的商品數量,假設10
行(商品),每行有 3 個數據列:
String[][] items = new String[10][3];
使用掃描儀 class 打開 stream 以接受鍵盤輸入:
Scanner userInput = new Scanner(System.in);
現在創建一個for
循環來遍歷數組中的每個項目行,以便用戶可以填充每個項目行。 以下是最簡單的形式,沒有驗證。 如果您在詢問項目名稱時只是按Enter鍵,則輸入過程將結束:
for (int i = 0; i < items.length; i++) {
System.out.print("Enter a name for item #" + (i + 1) + ": -> ");
String itemName = userInput.nextLine().trim();
if (itemName.isEmpty()) {
break;
}
System.out.print("Enter expiry for item #" + (i + 1) + ": -> ");
String itemExpiry = userInput.nextLine().trim();
System.out.print("Enter price for item #" + (i + 1) + ": -> ");
String itemPrice = userInput.nextLine().trim();
items[i][0] = itemName;
items[i][1] = itemExpiry;
items[i][2] = itemPrice;
System.out.println();
}
現在,將數組中包含的所有輸入項顯示到控制台 Window 中:
for (String[] diffItems : items) {
if (diffItems[0] != null) {
System.out.println(Arrays.toString(diffItems));
}
}
如果您更喜歡使用 2D arrays,首先您需要在自動售貨機中找到第一個“空”空間 -> null 元素。 (我會把它保存在一個方法中,這樣它就更清楚更容易使用了)
public int getFreeSpaceIndex(final String[][] vendingMachine) {
for (int index = 0; index < vendingMachine.length; index++)
if (vendingMachine[index] == null)
return index;
// meaning there's no empty space, you should use some static field
// to describe this situation to avoid magic numbers in your code
return -1;
}
找到元素后,您可以在其中插入所需的任何內容
// you've got the itemT1 array that you've created
// and let's say a user inputs the water item down below,
// I simplified it to declaration, cause it's off the topic
final String[] water = new String[] {"Water", "15"};
final int freeSpaceIndex = findFreeSpaceIndex(itemT1);
if (freeSpaceIndex == -1) {
System.err.printf("There's not enough space for the %s item.", Arrays.toString(water));
} else {
itemT1[freeSpaceIndex] = item;
}
最終,您可以將數組包裝到您自己的數據結構中,並簡單地創建一個addItem(String[])
方法,該方法將搜索空白空間並處理溢出。
class VendingMachineStock {
private String[][] stock = new String[][] {null, null, null, null, null, null, null, null, null};
// constructors, api...
public boolean hasFreeSpace() {
return getFreeSpaceIndex() != -1;
}
public boolean addItem(final String[] item) {
final int freeSpaceIndex = getFreeSpaceIndex();
if (freeSpaceIndex == -1) {
System.err.printf("There's not enough space for the %s item.", Arrays.toString(water));
return false;
}
stock[freeSpaceIndex] = item;
return true;
}
private int getFreeSpaceIndex() {
for (int index = 0; index < stock.length; index++)
if (stock[index] == null)
return index;
return -1;
}
}
但是這樣的代碼有很多缺陷。 任何人都可以搞砸並添加String[] {"15", "Water"}
甚至new String[] {"15", "30", "I'm Foo Bar:)"}
。
解決您的問題的正確數據結構實際上是帶有Item
對象的鏈表(如@DevilsHnd 所述)和您自己的限制結構。
class Item {
private final String name;
private int price;
// default getters, setters, consturctor...
}
class VendingMachineStock {
private final LinkedList<Item> stock;
// this will limit your stock list size
private int maxSlots;
// I omit API and constructor intentionally, it's off the
// topic, but you must write it
public void addItem(final Item item) {
// you can either throw exceptions or return boolean
// flag indicating the result, it's up to you.
// in this case I prefer a detailed explanation on why
// the method did not add the item.
if (stock.size() >= maxSlots) {
throw new IllegalStateException("Stock overflow, can't add more items");
}
stock.add(item);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.