目前我正在使用这种方法,但输出仅适用于前2位玩家而不是3或4位。
我想知道是什么让这个代码只适用于两个玩家,以及为什么它不会对其余玩家进行排序。此代码中的排序算法现在可以使用了。
public static void questions(String[] question, String[] answer, int n) {
String[] name = new String[n]; // Player Names
int[] playerscore = new int[n]; // Argument for Score
String[] que = new String[question.length]; //Questions for Loops
/* --------------------------- For loop for number of players --------------------------- */
for (int i = 0; i < n; i++)
{
playerscore[i] = 0;
name[i] = JOptionPane.showInputDialog("What is your name player "+ (i+1) +"?");
JOptionPane.showMessageDialog(null,"Hello : "+ name[i] + " Player number " +(i+1)+ ". I hope your ready to start!");
/* --------------------------- Loop in Loop for questions --------------------------- */
for (int x=0; x<question.length; x++) {
que[x] = JOptionPane.showInputDialog(question[x]);
if(que[x].equals(answer[x]))
{
playerscore[i] = playerscore[i] + 1;
}
else {
JOptionPane.showMessageDialog(null,"Wrong!");
}
} // End for loop for Question
// declare array and initialise with random elements
// print it out
for (int y=0; y<size; y++)
{
System.out.println("\nPlayer: "+(i+1)+ " Name: "+name[i]+" Score:"+playerscore[i]+" out of 5.");
}
System.out.println();
sort(playerscore);
// print it out again
for (int y=0; y<size; y++)
{
System.out.println("\nPlayer: "+(i+1)+ " Name: "+name[i]+" Score:"+playerscore[i]+" out of 5.");
}
System.out.println();
/* --------------------------- Loop in Loop for questions --------------------------- */
} // End for loop for player number
} //End method questions
while (!sorted)
{
// array potentially sorted
sorted = true;
//traverse array switching ill-ordered pairs
for (int i=0; i < playerscore.length-1; i++)
{
if (playerscore[i] > playerscore [i+1])
{
// swap them
int tmp = playerscore[i+1];
playerscore[i+1] = playerscore[i];
playerscore[i] = tmp;
// array wasn't sorted
sorted = false;
// write array so can see whats happening
write_array(playerscore);
}
}
}
}
static void write_array(int [] playerscore) { for(int i = 0; i&lt; playerscore.length; i ++) { System.out.print(playerscore [i] +“”); } 的System.out.println(); }
答案 0 :(得分:1)
使用
Arrays.sort( x );
表示String []以及int []。不要自己动手......
java.util.Arrays包含几个sort的定义:这称为重载。你不能通过编写单一的排序方法来做同样的事情。
答案 1 :(得分:0)
您是否考虑过使用泛型和Collection API,它上面有一个排序方法。
https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html