在Java中对整数数组进行排序和展平
我有一个介绍java类的项目,我们必须创建一个游戏,用户可以选择要使用的玩家数量、回合数和骰子数。当掷骰子时,骰子应该从大到小排序。我遇到的问题是将排序数组转换为int值(即4、3、2转换为432)。有没有一种方法可以合并数组,或者我必须创建一个循环?谢谢你的帮助,我希望这足够清楚,因为我的大脑中枪了
import java.util.Scanner;
/*
* @param args
*/
class beatThat {
public static void main(String[] args) {
int players = 0, rounds, dice, size, dValue, roundScore, a, b, t = 0;
Scanner playerInput;
playerInput = new Scanner(System.in);
// Thanks the user for playing the game.
// Asks for number of players.
System.out.println("Thank you for playing Beat That!");
// Picks number of players.
// If number of players not correct, requests selection again.
do {
System.out.println("Please pick your number of players (2-4):");
players = playerInput.nextInt();
} while (players < 2 | players > 4);
// Picks number of rounds.
// If number of rounds not correct, requests selection again.
do {
System.out.println("Please pick your number of rounds " +
"(max 15):");
rounds = playerInput.nextInt();
} while (rounds < 1 | rounds > 15);
// Picks number of dice.
// If number of dice not correct, requests selection again.
do {
System.out.println("Please pick your number of dice (max 7):");
dice = playerInput.nextInt();
} while (dice < 1 | dice > 7);
// Creates one dimensional array to hold dice values
int score [] = new int [dice];
// Generates random value between 1 & 6 for the amount of dice
// chosen and assigns them to the array.
for (int d = 0; d < dice; d++) {
dValue = (int)(Math.random() * 6) + 1;
System.out.print(dValue + ", ");
score [d] = dValue;
}
// Rearranges array from largest number to smallest number.
for (a=1; a < dice; a++) {
for (b = dice-1; b >= a; b--) {
if(score[b-1] < score[b]){
t = score[b-1];
score[b-1] = score[b];
score[b] = t;
}
}
}
////// // Can Delete. Prints out sorted array
System.out.println();
System.out.println("Sorted array is: ");
for (int i = 0; i < dice; i++)
System.out.print(score[i] + " ");
System.out.println("\n");
// Makes sorted array into one score.
int arrayLength = score.length;
int arrayIndex;
for (int i = 0; i < dice; i++) {
arrayIndex = (arrayLength - i - 1);
roundScore = score[i];
System.out.print("Your roundScore: ");
System.out.println(roundScore);
}
/////// End of Dice method
}
}
# 1 楼答案
首先将其存储在字符串中,然后将其转换回数字
Live demo
# 2 楼答案
使用循环,这是最好的方法。如果您对性能非常挑剔,请使用StringBuffer连接,然后转换为整数
但是,如果您只需要一行解决方案(不担心性能),那么要将整数数组转换为单个整数,请使用以下方法:
# 3 楼答案
循环可能是一种好方法。查看^{} :
# 4 楼答案
只需将骰子乘以每轮的基数:
在您的示例中,
{4, 3, 2}
给出了432
的分数,中间值为:0, 4, 43, 432
编辑
根据@PeterLawrey的建议重新措辞