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

标签 java arrays loops random joptionpane

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/

相关文章:

java - 如何在 Dagger 2 中使用@Scope

arrays - 在此对象上找不到 PowerShell 属性 Count

ios - 数组中的 NSNumber,ios

linux - 在 bash 中循环遍历不相关的数字范围时使用文件中的行

java - Eclipselink/ Derby : Foreign Key Constraint

Java 1.8 安全点超时

java - 重写 Java 中的赋值运算符

JavaScript - 将四字符数组转换为整数

php - 将多个文本文件导入到mysql数据库中的不同表中

arrays - 迭代 Go 字符串以提取特定的子字符串