簡體   English   中英

存儲結果

[英]Storing results

我正在使用Java做一些作業,這就是我應該做的。 給定一個整數X ,您應該讀取X行,每行包含一個字符串以及2個整數值xy

**Input**
2 <-- Read 2 lines
PLUS 10 30 <-- PLUS refers to adding 30 to 10
MINUS -6 20 <-- MINUS refers to minus 20 from -6
**Output**
40 
-26

如何存儲40和-26的值? 我當前正在使用數組。 下面的代碼。

for(int i = 0; i < limit; i++)
{
    String limitInput = sc.next();
    x = sc.nextInt();
    y = sc.nextInt();
    if(limitInput.equals("PLUS"))
    {
        System.out.println(x+y);
        limitArray[i] = x + y;
    }
    else if(limitInput.equals("MINUS"))
    {
        limitArray[i] = x - y;
    }
    else
    {
        limitArray[i] = x * y;
    }
}

有沒有像不使用數組那樣的簡單方法?

對於您的案例,不要認為數據結構比數組簡單。 如果要與操作/行號一起存儲結果; 會建議您使用HashMap。 但是, map絕對比數組簡單。

 Map<Integer,Integer> map = new HashMap<Integer,Integer>();
 int line = 1; //read line number
 int result= 40;  //read final result
 map.put(line, result); 

這樣,您可以通過迭代地圖獲得每一行的結果。

但是,如果您還想存儲已執行的操作,請執行以下操作: 然后建議使用像這樣的多重地圖

 Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
 ArrayList<String> a = new ArrayList<String>(); 
 a.add("PLUS"); //add operation
 a.add(result); //add result

 map.put(line, a);

從列表中讀取值時; 只需確保將值(在位置1處)解析為int(存儲為String)即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM