菜鸟问一个random的问题!

studymanshxq 2005-12-02 10:59:19
我想生成一个(1~9)4位数,4个数字不能一样。我这样的写法还是会生成0和相同的数字,不知道应该怎么改,谢谢各位帮助一下。。


public class number
{

public static void main(String[] args)
{
String z[] = new String [4];
int x;
int a[] = new int[4];
double y;
for(int i=0;i<=3;i++)
{
y=Math.random()*10;
x=(int)y;
a[i] = x;
/*z[i] = String.valueOf(x);*/
if(a[0]==0&&a[0]==a[1]&&a[0]==a[2]&&a[0]==a[3]&&a[1]==a[2]&&a[1]==a[3]&&a[2]==a[3])
{
i=0;
}
else
z[i]= String.valueOf(x);



}
for(int k=0;k<=3;k++)
{
System.out.print(z[k]);
}
}


}
...全文
167 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kingfish 2005-12-03
  • 打赏
  • 举报
回复
if(a[0]==0||(你的其它条件))
==
TONYBLARED 2005-12-03
  • 打赏
  • 举报
回复
public static void main(String[] args) {
int count = 0;
int value;
Integer inte;
HashMap map = new HashMap();
while(count < 4){
value = (int)(Math.random() * 10);
if(value == 0){
continue;
}
inte = Integer.valueOf(value);
if(!map.containsKey(inte)){
map.put(inte,"");
System.out.println("value is "+value);
count++;
}
}
}
shouyenet1 2005-12-03
  • 打赏
  • 举报
回复
if(a[0]==0&&a[0]==a[1]&&a[0]==a[2]&&a[0]==a[3]&&a[1]==a[2]&&a[1]==a[3]&&a[2]==a[3])
有问题
studymanshxq 2005-12-03
  • 打赏
  • 举报
回复
if(a[0]==0&&a[0]==a[1]&&a[0]==a[2]&&a[0]==a[3]&&a[1]==a[2]&&a[1]==a[3]&&a[2]==a[3])
这样的语句存在什么问题
jimmy_kuu 2005-12-03
  • 打赏
  • 举报
回复
//我写的这段,应该能满足你的要求
public class RanNumber {
public static void main(String[] args) {
String[] z = new String[4];

for (int i = 0; i < 4; i++) {
int temp = 0;
boolean flag = true;

while (flag) {
temp = (int)(Math.random() * 10);

if (temp == 0)
continue;

flag = false;

for (int j = 0; j < i; j++) {
if (z[j].equals(String.valueOf(temp))) {
flag = true;

break;
}
}
}

z[i] = String.valueOf(temp);
}
for (int i = 0; i < 4; i++)
System.out.print(z[i]);
}
}

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧