我有一个程序,可以接收乐队和专辑的文件列表。我需要确定每个乐队制作的专辑数量,然后打印出乐队列表以及他们按降序制作的专辑数量。我环顾四周,看到它是使用映射和集合完成的。我想知道怎么做都不要。这是我到目前为止的内容:
public static void processFile(String filename)
{
String bandname = "";
String[][] data = read_spreadsheet(filename);
//takes the file and converts it to a 2d array
ArrayList<String> bands = new ArrayList<String>();
for(int rows = 0; rows < data.length; rows++)
{
bands.add(data[rows][0]);
}
for(int i = 0; i<bands.size()-1;i++)
{
int albumcount = 0;
for(int j = i+1; j<bands.size();j++)
{
if(bands.get(i).equals(bands.get(j)))
{
albumcount++;
}
}
}
}
输入示例:
band1 -album
band2 -album
band1 -album
band3 -album
band1 -album
band2 -album
输出示例:
band1: 3
band2: 2
band3: 1
最佳答案
没有收藏?您要使用数组吗?
String [] names = new String[data.length];
int [] counts = new int[data.length];
int j = 0;
for (int i = 0; i < data.lenght; i++ ) {
while (j < data.length) {
if (data[i][0].equals(names[j])) {
found = true;
counts[j]++;
break;
} else if (names[j] == null) {
names[j] = data[i][0];
counts[j]=1;
break;
}
j++;
}
}
// find max count
// println
// nullify element
// repeat
for (int i = 0; i < j; i++) {
int max = -1;
int k = i;
int pos = -1;
while ( k < j ) {
if ( counts[k] > max ) {
pos = k;
max = counts[k];
}
k++;
}
if ( pos != -1 ) { // we found
System.out.println ( names[pos] + ": " + counts[pos]);
counts[pos] = -1;
}
}