java编程 随机交换数组元素
假如我有一个数组a[6]=(1,2,3,4,5,6),我想随机交换数组中的两个元素,应该怎么写?...
假如我有一个数组a[6]=(1,2,3,4,5,6),我想随机交换数组中的两个元素,应该怎么写?
展开
2个回答
展开全部
import java.util.Random;
public class Test1111 {
public static void main(String[]args){
int flag = 0;
int []a={1,2,3,4,5,6};
Random rand = new Random();
int place_1 = rand.nextInt(6);
int place_2 = rand.nextInt(6);
while(true){
if(place_1 != place_2){
break;
}
}
flag = a[place_1];
a[place_1] = a[place_2];
a[place_2] = flag ;
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
}
}
没做优化,大概就这样的
public class Test1111 {
public static void main(String[]args){
int flag = 0;
int []a={1,2,3,4,5,6};
Random rand = new Random();
int place_1 = rand.nextInt(6);
int place_2 = rand.nextInt(6);
while(true){
if(place_1 != place_2){
break;
}
}
flag = a[place_1];
a[place_1] = a[place_2];
a[place_2] = flag ;
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
}
}
没做优化,大概就这样的
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
import java.util.Random;
public class RandomArray
{
public static void main(String[] args)
{
int[] a = {1,2,3,4,5,6,7,8,9};
Random random = new Random();
int ran = random.nextInt(a.length);
int ran2 = 0;
while (true)
{
ran2 = random.nextInt(a.length);
if (ran2 != ran)
{
break;
}
}
int i = a[ran];
a[ran] = a[ran2];
a[ran2]= i;
for (int j : a)
{
System.out.print(j);
}
}
}
public class RandomArray
{
public static void main(String[] args)
{
int[] a = {1,2,3,4,5,6,7,8,9};
Random random = new Random();
int ran = random.nextInt(a.length);
int ran2 = 0;
while (true)
{
ran2 = random.nextInt(a.length);
if (ran2 != ran)
{
break;
}
}
int i = a[ran];
a[ran] = a[ran2];
a[ran2]= i;
for (int j : a)
{
System.out.print(j);
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询