
java【不用list】如何将数组元素顺序打乱
String[]cards={"A","2","3","4","5","6","7","8","9","10","J","Q","K"}打乱顺序不用list<>...
String[] cards = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}
打乱顺序 不用list<> 展开
打乱顺序 不用list<> 展开
展开全部
public class RandomNumber {
public static void main(String[] args) {
String[] cards = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
for (int i = 0; i < 10; i++) {
int firstIndex = (int) (Math.random() * Math.round(cards.length));
int secondIndex = (int)(Math.random() * Math.round(cards.length));
if (firstIndex == secondIndex)
continue;
String temp = cards[firstIndex];
cards[firstIndex]=cards[secondIndex];
cards[secondIndex]=temp;
}
for(String s:cards)
System.out.println(s);
}
}
//望采纳,谢谢
public static void main(String[] args) {
String[] cards = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
for (int i = 0; i < 10; i++) {
int firstIndex = (int) (Math.random() * Math.round(cards.length));
int secondIndex = (int)(Math.random() * Math.round(cards.length));
if (firstIndex == secondIndex)
continue;
String temp = cards[firstIndex];
cards[firstIndex]=cards[secondIndex];
cards[secondIndex]=temp;
}
for(String s:cards)
System.out.println(s);
}
}
//望采纳,谢谢
展开全部
这好办得很嘛, 假如长度为10, 从10内随机取一个数,把改下标的值和下标0互换, 换个10次或者更高就行了
追问
能贴个代码吗
追答
public static void main(String[] args) {
String[] cards = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
int len = cards.length;
java.util.Random ran = new java.util.Random();
for(int i = 0;i < 10;i++){
int temp = ran.nextInt(len);
String c = cards[temp];
cards[temp]=cards[0];
cards[0]=c;
}
for(int i = 0;i < len; i++){
System.out.print(cards[i]+" ");
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询