回 帖 发 新 帖 刷新版面

主题:求助

请教各位高手,如何用JAVA实现一个动态数组,用随机函数为数组里的元素赋值,请附上源代码,谢谢各位

回复列表 (共3个回复)

沙发

import java.util.Random;

public class RandomDemo 
{
    public static void main(String[] args)
    {
        Random r = new Random();
        int [] num = new int [r.nextInt(20)];
        
        for(int i=0;i<num.length;i++)
        {
            num[i] = r.nextInt(100);
            System.out.print(num[i]+"\t");
        }
        
        System.out.println();
    }
}

板凳

请教这位高手,如果我想用一个时间函数来控制,每一秒都随机给数组里的元素赋值如何实现

3 楼

import java.util.Random;


public class RandomDemo implements Runnable
{
    private  Random r = new Random();
    private int [] num;
    

    public static void main(String[] args)
    {
        Thread t = new Thread(new RandomDemo());
        t.start();
    }

    public void run()
    {
        while(true)
        {
            try 
            {
                num = new int [r.nextInt(20)];
                
                for(int i=0;i<num.length;i++)
                {
                    num[i] = r.nextInt(100);
                    System.out.print(num[i]+"\t");
                }
                
                System.out.println();
                
                Thread.sleep(1000);
            }
            catch (Exception e)
            {
                
            }
        }
    }
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册