先看看我的一个类,很短,耐心看看哦。
我是希望从这个类中得到四个不同的0-9的数,但是编译运行后,有时候能得到,有时候又得不到,不知道到底哪里出错了,请各位高手指点。另外如果有更好的方法得到四个不同的0-9的数的方法还望不吝赐教!!!先谢谢各位咯!!class begin implements Runnable
{
int a[]=new int[4];
int p=0;
public void run()
{ for(int i=0;i<4;i++)
{
a[i]=(int)(Math.random()*9)+1;
while(p<i)
{
for(int j=0;j<i;j++)
{
if(a[i]==a[j])
{
a[i]=(int)(Math.random()*9)+1;
p=0;
break;
}
else
{
p++;
}
}
}
}
}}
我是希望从这个类中得到四个不同的0-9的数,但是编译运行后,有时候能得到,有时候又得不到,不知道到底哪里出错了,请各位高手指点。另外如果有更好的方法得到四个不同的0-9的数的方法还望不吝赐教!!!先谢谢各位咯!!class begin implements Runnable
{
int a[]=new int[4];
int p=0;
public void run()
{ for(int i=0;i<4;i++)
{
a[i]=(int)(Math.random()*9)+1;
while(p<i)
{
for(int j=0;j<i;j++)
{
if(a[i]==a[j])
{
a[i]=(int)(Math.random()*9)+1;
p=0;
break;
}
else
{
p++;
}
}
}
}
}}
if(a[i]==a[j])
{
a[i]=(int)(Math.random()*9)+1;
p=0;
break;
}
这里的p=0这句没有起作用,我在另外一个class里面的main方法中运行时候调用这里的p,发现p的值好大啊。
public class first
{
public static int a[]=new int[4];
int p=0;
public void run()
{ for(int i=0;i<4;i++) {
a[i]=(int)(Math.random()*9)+1;
while(p<i)
{ for(int j=0;j<i;j++)
{
if(a[i]==a[j])
{
a[i]=(int)(Math.random()*9)+1;
p=0;
break;
}
else
{
p++;
} }
}
p=0;
}
}
public static void main(String args[])
{
new first().run();
for(int i=0;i<4;i++)
{
System.out.println(a[i]);
}
}}
{
int a[]=new int[4];
int p=0;
public void run()
{ for(int i=0;i<4;i++)
{
a[i]=(int)(Math.random()*9)+1;
while(p<i)
{
for(int j=0;j<i;j++)
{
if(a[i]==a[j])
{
a[i]=(int)(Math.random()*9)+1;
p=0;
break;
}
else
{
p++;
}
}//for
}//while
p=0;//关键
}//for
}//void run()}//class
for (int i = 0; i < 4; i++)
{
int p = 0;
a[i] = (int) (Math.random() * 9) + 1;
while (p < i) {
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[i] = (int) (Math.random() * 9) + 1;
p = 0;
break;
}
else {
p++;
}
}
}
}
for(int i=0;i<4;i++){
System.out.println(a[i]);
}
另外(int) (Math.random() * 9) + 1产生的随机数是[1,9]而不是楼主要求的[0,9]
可以用java.util.Random.nextInt(int)方法来替代
import java.util.*;
public class begin implements Runnable
{
static ArrayList array = new ArrayList();
public void run()
{
Random rand = new Random();
boolean success = false;
for(int i=0;i<4;i++)
{
success = false;
Integer integer = new Integer(rand.nextInt(10));
while(!success)
{
if(!array.contains(integer))
{
success = true;
array.add(integer);
}
else
integer = new Integer(rand.nextInt(10));
}
}
}
public static void main(String[] args)
{
new begin().run();
System.out.println(array);
}
}