java获得一个随机数,把这个随机数当做数组下标,并且不能重复
我的意思是,这十个String类型的元素要根据随机数下标乱序输出,但不能重复。怎么做求大神解答!!谢谢!publicstaticvoidmain(String[]args...
我的意思是,这十个String类型的元素要根据随机数下标乱序输出,但不能重复。
怎么做求大神解答!!谢谢!
public static void main(String[] args) {
String[] name = new String[] { "啊", "是", "恶", "他", "从", "不", "想", "他",
"我", "饿 };
int a = (int) (Math.random() * 9); 展开
怎么做求大神解答!!谢谢!
public static void main(String[] args) {
String[] name = new String[] { "啊", "是", "恶", "他", "从", "不", "想", "他",
"我", "饿 };
int a = (int) (Math.random() * 9); 展开
2个回答
2016-07-28
展开全部
static ArrayList<Integer> indexs = new ArrayList<>();
public static void main(String[] args) {
String[] name = new String[]{"啊", "是", "恶", "他", "从", "不", "想", "他", "我", "饿"};
int n = name.length;
int i = 0;
while (i < n) {
int rnd = (int) (Math.random() * n);
if (!indexs.contains(rnd)) {
indexs.add(rnd);
i++;
}
}
for (int index : indexs) {
System.out.println(index + " " + name[index]);
}
}
追问
谢谢!手快没选你
展开全部
用List来替代数组,选中一个,从List中删除一个,保证不会重复。
import java.util.*;
public class Test
{
public static void main(String[] args)
{
String[] name=new String[]{"1","2","3","4","5","6"};//此处替换为你自己的字符串
List<String> listName=new ArrayList<String> ();
for(String s:name)
listName.add(s);
Random r=new Random();
while(listName.size()>0)
{
int i=r.nextInt(listName.size());
// String str=;
System.out.println(listName.get(i));
listName.remove(i);
}
}
}
import java.util.*;
public class Test
{
public static void main(String[] args)
{
String[] name=new String[]{"1","2","3","4","5","6"};//此处替换为你自己的字符串
List<String> listName=new ArrayList<String> ();
for(String s:name)
listName.add(s);
Random r=new Random();
while(listName.size()>0)
{
int i=r.nextInt(listName.size());
// String str=;
System.out.println(listName.get(i));
listName.remove(i);
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询