[英]Java - Issue in organizing 2D Array based on first column
我正在嘗試組織一個2D Array
,其中包含游戲標題及其等級:
我有一個像這樣的2D array
:
Super Luigi Planet, 4
Nomopoly 2
Pac-Dude 5
Settlers of Catan 5
Super Luigi Planet 3
Nomopoly 5
Pac-Dude 1
Nomopoly 3
Pac-Dude 5
在按第一列按字母順序對2D Array
排序之后,我想將數組分成多個2D Arrays
如下所示:
Nomopoly 2
Nomopoly 3
Nomopoly 5
Pac-Dude 5
Pac-Dude 1
Pac-Dude 5
Settlers of Catan 5
Super Luigi Planet 3
Super Luigi Planet 4
我不確定如何分離2D array
。 如果我能夠將2D array
與游戲和數組分離成多個數組,那么找到游戲的平均評分會容易得多,這就是我想要看到的。
我認為您最好使用2D數組以外的數據結構,例如TreeMap<String, List<Integer>>
。 TreeMap
的優點在於,它會根據鍵(在這種情況下為第一列)自動按字母順序排序。
因此,您構造數據的方式將如下所示:
壟斷:[2、3、5]
Pac-Dude:[5,1,5]
卡坦定居者:[5]
超級路易吉星球:[3,4]
然后,您所要做的就是將輸入(可能是使用String.split()
解析到結構中。 當您要顯示它時,請遍歷地圖的鍵和列表的元素,並將其聚合為所需的格式。
我不確定是否需要為此項目/任務拆分陣列。 但是我認為有一種更簡單的方法,不需要將原始數組拆分為更多的數組。 您只需要在主數組中找到標題,然后計算標題的平均評分即可。 我編寫了一個示例,但沒有對其進行測試。 我希望它能給您一些想法。
import java.util.Scanner;
公共類游戲{
private String data[][];
private int size;
private int last_line;
Games() {
data = new String[100][2];
size = 0;
last_line = 0;
}
public void addTitle() {
Scanner input = new Scanner(System.in);
String title;
int rating = -1;
System.out.print("Enter the title of the game:");
title = input.next();
System.out.print("Enter the rating of " + title + ":");
rating = input.nextInt();
while (rating > 5 || rating < 0) {
System.out.println("Invalid entry. Please enter the rating from 0 to 5");
rating = input.nextInt();
}
data[last_line][0] = title;
data[last_line][1] = String.valueOf(rating);
this.last_line++;
this.size++;
}
public double getAverage(String key) {
int rating_count = 0;
int number = 0;
double average;
for (int i = 0; i < size; i++) {
if (data[i][0].equalsIgnoreCase(key)) {
rating_count += Integer.parseInt(data[i][1]);
number++;
}
}
average = rating_count / number;
return average;
}
public static void main(String[] args) {
// TODO code application logic here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.