gpt4 book ai didi

java - 如何让生成的数字立即显示?

转载 作者:行者123 更新时间:2023-11-30 11:15:22 25 4
gpt4 key购买 nike

import java.util.*;
import javax.swing.JOptionPane;
public class p1
{
public static void main(String[] args)
{
int size = 50;

ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++)
{
list.add(i);
}

Random rand = new Random();
while(list.size() > 0)
{
int index = rand.nextInt(list.size());
JOptionPane.showMessageDialog(null, "Selected: "+list.remove(index));
}
}
}

当我运行这个程序时,我生成的随机数都显示在单独的消息框中,我该如何更改代码以便它在一个消息框中显示数组,即。您生成的数字是:1、4、5、6、33 等。)还有我如何更改代码以使其生成一定数量的数字,比如 10,因为据我所知它打印出 50 .

最佳答案

除了这样做:

JOptionPane.showMessageDialog(null, "Selected: "+list.remove(index));

将 list.remove(index) 放入一个字符串变量中

然后在循环之后放

  JOptionPane.showMessageDialog(null, "Selected: "+string variable);

你的错误只是将对话框放在循环之外。

public static void main(String[] args) 
{
int size = 10;

ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++)
{
list.add(i);
}

Random rand = new Random();
String buffer = "";
while(list.size() > 0)
{
int index = rand.nextInt(list.size());
buffer += ","+list.remove(index);

}
JOptionPane.showMessageDialog(null, "Selected: "+buffer);
}

编辑答案:必须制作两个变量大小和范围

public static void main(String[] args) 
{
int size = 10;
int range = 50;

ArrayList<Integer> list = new ArrayList<Integer>(size);
Random rand = new Random();
for(int i = 1; i <= size; i++)
{
list.add( rand.nextInt(range));
}


String buffer = "";
while(list.size() > 0)
{
int index = 0;

if(list.size() != 1)
buffer += list.remove(index)+",";
else if(list.size() == 1)
buffer += list.remove(index)+",";
index++;
}
JOptionPane.showMessageDialog(null, "Selected: "+buffer);
}

关于java - 如何让生成的数字立即显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com