以下是我的代码,但它不会生成唯一的随机数
Random rand = new Random();
int[] array = new int[n];
for (int i = 0; i < n; i++){
array[i] = rand.nextInt(n)+1;
}
for (int i = 0; i < ( n - 1 ); i++)
{
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j+1]){
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
答案 0 :(得分:0)
public TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView);
Random r = new Random();
StringBuffer temp =new StringBuffer("Random numbers:");
for(int i=0;i<10;i++) {
int i1 = r.nextInt(100 - 0) + 0;
temp.append(String.valueOf(i1));
temp.append(String.valueOf(" "));
}
tv.setText(temp.toString());
}
//here ,,I generate 10 random numbers and save it in to stringBuffer and dispaly it in to textView..here range is up to 0 to 100...you can take your own Range ...I hope ,,It will help you...
答案 1 :(得分:0)
检查一下!...它对我有用
Random rand = new Random();
int n = 10;
int[] array = new int[n];
for (int i = 0; i < n; i++){
array[i] = (int) (rand.nextDouble() * n + 1);
}
for (int i = 0; i < ( n - 1 ); i++)
{
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j+1]){
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (int piece: array) {
System.out.println(piece);
}