我希望能够使用相应的名称从最高到最低对这些数组进行排序。我创建了一种方法来帮助我将数组分数从最低到最高缩短,但我无法找到一种将名称和分数链接在一起以便能够一起打印的方法。 (出于同样的原因,我没有调用我的方法)
import java.util.*;
/**
* This program will prompt the user to enter the number of game players,
* the game players' names, and their scores, and prints game players name
* and scores in decreasing order of their scores.
*
*/
//class name
public class SortGameScores
{
// main program start
public static void main(String[] args)
{
//declaring variable
int numberOfPlayers;
//create new scanner
Scanner input = new Scanner(System.in);
//Ask user to enter number of players and record number
System.out.print("Enter number of players: ");
numberOfPlayers = input.nextInt();
//Create and declare arrays using previous input
int[] player = new int [numberOfPlayers];
String[] name = new String[numberOfPlayers];
int[] score = new int [numberOfPlayers];
//Ask user to enter each player's name
for (int i = 0; i < player.length; i++)
{
System.out.print("Enter player's name: ");
name[i] = input.next();
}
//Ask user to enter each player's score
for (int i = 0; i < player.length; i++)
{
System.out.print("Enter player's score: ");
score[i] = input.nextInt();
}
//Print name and score for each array.
for (int i = 0; i < numberOfPlayers; i++)
{
System.out.println("Player: " + name [i] + " , " + "score: " + score [i]);
}
}//Close Main
//method that will assort each score lowest to highest
public static void selectionSort(int[] list)
{
for (int i = 0; i < list.length - 1; i++)
{
int currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++)
{
if (currentMin > list[j])
{
currentMin = list[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i)
{
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}//Close method selectionSort
}//close Class
最佳答案
问题在于您使用的是两个并行数组,而不是使用包含对象的单个数组。
创建一个类Player
,带有 name
和一个 score
字段,创建 Player
的数组s,并按得分对玩家进行排序(使用 Comparator<Player>
)。
关于Java 数组 : Sorting scores and displaying with proper name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36897412/