[英]how exit from the following infinite loop in java but still fill vector till 100 with unique values?
i want to create vector of big length from unique values without repetition but the following code enter in infinite loop . 我想从唯一值创建大长度的向量而无需重复,但是以下代码进入无限循环。
public static void main(String[] args) {
// TODO code application logic here
Vector v1=new Vector(100);
Vector v2=new Vector(100);
Random r=new Random();
int i=0;
while(i<100){
double val=Math.abs(r.nextGaussian());
double h=(double)((double)Math.round(val*10)/10.0);
if (!v1.contains(h)){
v1.add(h);
i++;
}
}
for(int j=0;j<v1.size();j++)
v2.set(j, v1.get(j));
}
}
First, don't use raw types ( Collection<Double>
, not just raw Collection
). 首先,不要使用原始类型(
Collection<Double>
,而不仅仅是原始Collection
)。 Second, you want a Set
(not a Vector
) and assuming you need to preserve the original order you can use a LinkedHashSet
. 其次,您需要一个
Set
(而不是Vector
),并假设需要保留原始顺序,则可以使用LinkedHashSet
。 You can test the Set
size until you have one hundred values. 您可以测试
Set
大小,直到有一百个值。 And, you don't need any of those casts in assigning h
(and you need to remember the count you want - if you use 10
you are limiting your value range to 1
to 10
). 而且,在分配
h
不需要任何这些强制转换(并且您需要记住想要的计数-如果使用10
则将值范围限制为1
到10
)。 Like, 喜欢,
Set<Double> set = new LinkedHashSet<>();
Random r = new Random();
int count = 100;
while (set.size() < count) {
double val = Math.abs(r.nextGaussian());
double h = Math.round(val * count) / 10.0;
set.add(h);
}
System.out.println(set);
You could also write the while
loop like 您也可以编写
while
循环,例如
while (set.size() < count) {
set.add(Math.round(Math.abs(r.nextGaussian()) * count) / 10.0);
}
Or, if using Java 8+, you could use a DoubleStream
and distinct()
with limit(int)
with a lambda. 或者,如果使用Java 8+,则可以使用
DoubleStream
和带有带有lambda的limit(int)
distinct()
。 Like, 喜欢,
Random r = new Random();
int count = 100;
Set<Double> set = DoubleStream.generate(() -> Math.round(
Math.abs(r.nextGaussian()) * count) / 10.0).boxed()
.distinct().limit(count).collect(Collectors.toSet());
System.out.println(set);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.