【发布时间】:2014-03-30 01:37:40
【问题描述】:
我正在参加 Java 的 100 级课程...非常新,这是我的第一个问题,请多多包涵:)。
我有一个任务,其中两个用户要输入他们的姓名,然后获取他们玩过的游戏数,然后获取他们玩过的每场游戏的分数,将分数放入一个数组(或两个数组???) ,然后比较两个数组和分数,看看谁赢得了每场比赛,或者他们是否并列,然后显示结果。我不相信我不必对其进行排序或搜索。
我的老师说获取分数必须是一个 void 方法,但我不确定如何将这个 void 方法中的值获取到每个玩家的数组中,以便我可以比较分数值。
这是我将分数放入数组的方法:
public static void inputScores(int[] array, String msg) {
String inputScores = "";
for (int i = 1; i < array.length; i++) {
inputScores = JOptionPane.showInputDialog(msg + " enter your score for game " + i);
array[i] = Integer.parseInt(inputScores);
}
}
这是我的主要方法:
public static void main(String[] args) {
//Get the number of games from the user, this is the array length
int[] numberOfGamesPlayed = new int[getPositiveIntOrQuit("How many games were played?")];
//Get the names of the players (Two)
String input, input2 = "";
input = JOptionPane.showInputDialog("Player 1 - enter your name");
inputScores(numberOfGamesPlayed, input);
input2 = JOptionPane.showInputDialog("Player 2 - enter your name");
inputScores(numberOfGamesPlayed, input2);
//Get two separate arrays, one for Player1, one for Player2
String output = "";
showResults(WINDOW_TITLE, output);
}
}
是的,这有点乱,但我正在尝试自己解决这个问题。这是我的 compareScores 方法,但我知道这很疯狂。我已经尝试过解决它,但是是的,它变得越来越困难。
public static String compareScores(int[] playerOne, int[] playerTwo, String msg, String msg2) {
String output = "";
int player1Wins = 0;
int player2Wins = 0;
int tie = 0;
for(int i = 0; i < playerOne.length; i++) {
for(int j = 0; j < playerTwo.length; j++); {
if(playerOne[i] > playerTwo[i]) {
output += "Game " + i + " results:" + "\n" + msg + " outscored " + msg2
+ " by " + (playerOne[i] - playerTwo[i]) + "points.";
player1Wins++;
}
else if(playerOne[i] < playerTwo[i]) {
player2Wins++;
output += "Game " + i + " results:" + "\n" + msg2 + " outscored " + msg
+ " by " + (playerTwo[i] - playerOne[i]) + "points.";
}
else {
output += msg + " and " + msg2 + " scored the same number of points.";
tie++;
}
}
output += "Summary: ";
}
return output;
}
是的,我知道这很多,而且我不擅长解释,但如果有人可以帮助我,我不介意尝试解释更多正在发生的事情,如果这意味着获得帮助,因为我真的被困得疯了现在。
感谢所有帮助/)
【问题讨论】:
-
关于一般的 void 方法,请阅读“通过引用传递”。如果将对象的引用作为参数传递给方法,则不必返回任何内容,因为您已经拥有对实际对象的引用,并且可以更改对象的值。我认为在你的情况下,你正在接受分数,你可以在你的主要方法中做到这一点,它是 void 类型。
-
谢谢!我的老师是这么说的。所以,我会继续努力,对参考传递做更多的研究(我现在对方法还是很陌生),看看我能解决什么问题。 @prash