Example usage for java.util Random nextInt

List of usage examples for java.util Random nextInt

Introduction

In this page you can find the example usage for java.util Random nextInt.

Prototype

public int nextInt() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

Usage

From source file:MainClass.java

public static void main(String args[]) {
    Random generator = new Random(100);

    System.out.println("First generator:");
    for (int i = 0; i < 10; i++)
        System.out.println(generator.nextInt());

}

From source file:Main.java

public static void main(String args[]) {

    Random randomno = new Random();

    // setting seed
    randomno.setSeed(20);/*from  w  w w . j av a2  s .  c o m*/

    // value after setting seed
    System.out.println("Object after seed: " + randomno.nextInt());
}

From source file:Random2.java

public static void main(String[] argv) {
    //+/* ww  w  . j ava 2 s .  com*/
    // java.util.Random methods are non-static, so need to construct
    Random r = new Random();
    for (int i = 0; i < 10; i++)
        System.out.println("A double from java.util.Random is " + r.nextDouble());
    for (int i = 0; i < 10; i++)
        System.out.println("An integer from java.util.Random is " + r.nextInt());
    //-
}

From source file:com.yahoo.ads.pb.mttf.PistachiosMTTFTest.java

public static void main(String[] args) {
    PistachiosClient client;//  ww  w  .j  a  v a  2 s  . c o m
    try {
        client = new PistachiosClient();
    } catch (Exception e) {
        logger.info("error creating client", e);
        return;
    }
    Random rand = new Random();

    while (true) {
        try {
            long id = rand.nextLong();
            String value = InetAddress.getLocalHost().getHostName() + rand.nextInt();
            client.store(0, id, value.getBytes());
            for (int i = 0; i < 30; i++) {
                byte[] clientValue = client.lookup(0, id);
                String remoteValue = new String(clientValue);
                if (Arrays.equals(value.getBytes(), clientValue)
                        || !remoteValue.contains(InetAddress.getLocalHost().getHostName())) {
                    logger.debug("succeeded checking id {} value {}", id, value);
                } else {
                    logger.error("failed checking id {} value {} != {}", id, value, new String(clientValue));
                    System.exit(0);
                }
                Thread.sleep(100);
            }
        } catch (Exception e) {
            System.out.println("error testing" + e);
            System.exit(0);
        }
    }
}

From source file:org.eclipse.swt.snippets.Snippet192.java

public static void main(String[] args) {
    // initialize data with keys and random values
    int size = 100;
    Random random = new Random();
    final int[][] data = new int[size][];
    for (int i = 0; i < data.length; i++) {
        data[i] = new int[] { i, random.nextInt() };
    }/*from  w  ww. j a va  2 s . co m*/
    // create a virtual table to display data
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 192");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.VIRTUAL);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    table.setItemCount(size);
    final TableColumn column1 = new TableColumn(table, SWT.NONE);
    column1.setText("Key");
    column1.setWidth(200);
    final TableColumn column2 = new TableColumn(table, SWT.NONE);
    column2.setText("Value");
    column2.setWidth(200);
    table.addListener(SWT.SetData, e -> {
        TableItem item = (TableItem) e.item;
        int index = table.indexOf(item);
        int[] datum = data[index];
        item.setText(new String[] { Integer.toString(datum[0]), Integer.toString(datum[1]) });
    });
    // Add sort indicator and sort data when column selected
    Listener sortListener = e -> {
        // determine new sort column and direction
        TableColumn sortColumn = table.getSortColumn();
        TableColumn currentColumn = (TableColumn) e.widget;
        int dir = table.getSortDirection();
        if (sortColumn == currentColumn) {
            dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
        } else {
            table.setSortColumn(currentColumn);
            dir = SWT.UP;
        }
        // sort the data based on column and direction
        final int index = currentColumn == column1 ? 0 : 1;
        final int direction = dir;
        Arrays.sort(data, (a, b) -> {
            if (a[index] == b[index])
                return 0;
            if (direction == SWT.UP) {
                return a[index] < b[index] ? -1 : 1;
            }
            return a[index] < b[index] ? 1 : -1;
        });
        // update data displayed in table
        table.setSortDirection(dir);
        table.clearAll();
    };
    column1.addListener(SWT.Selection, sortListener);
    column2.addListener(SWT.Selection, sortListener);
    table.setSortColumn(column1);
    table.setSortDirection(SWT.UP);
    shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:TableSortTwoDirection.java

public static void main(String[] args) {
    // initialize data with keys and random values
    int size = 100;
    Random random = new Random();
    final int[][] data = new int[size][];
    for (int i = 0; i < data.length; i++) {
        data[i] = new int[] { i, random.nextInt() };
    }/*from ww w . j  a  v  a  2 s  .com*/
    // create a virtual table to display data
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.VIRTUAL);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    table.setItemCount(size);
    final TableColumn column1 = new TableColumn(table, SWT.NONE);
    column1.setText("Key");
    column1.setWidth(200);
    final TableColumn column2 = new TableColumn(table, SWT.NONE);
    column2.setText("Value");
    column2.setWidth(200);
    table.addListener(SWT.SetData, new Listener() {
        public void handleEvent(Event e) {
            TableItem item = (TableItem) e.item;
            int index = table.indexOf(item);
            int[] datum = data[index];
            item.setText(new String[] { Integer.toString(datum[0]), Integer.toString(datum[1]) });
        }
    });
    // Add sort indicator and sort data when column selected
    Listener sortListener = new Listener() {
        public void handleEvent(Event e) {
            // determine new sort column and direction
            TableColumn sortColumn = table.getSortColumn();
            TableColumn currentColumn = (TableColumn) e.widget;
            int dir = table.getSortDirection();
            if (sortColumn == currentColumn) {
                dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
            } else {
                table.setSortColumn(currentColumn);
                dir = SWT.UP;
            }
            // sort the data based on column and direction
            final int index = currentColumn == column1 ? 0 : 1;
            final int direction = dir;
            Arrays.sort(data, new Comparator() {
                public int compare(Object arg0, Object arg1) {
                    int[] a = (int[]) arg0;
                    int[] b = (int[]) arg1;
                    if (a[index] == b[index])
                        return 0;
                    if (direction == SWT.UP) {
                        return a[index] < b[index] ? -1 : 1;
                    }
                    return a[index] < b[index] ? 1 : -1;
                }
            });
            // update data displayed in table
            table.setSortDirection(dir);
            table.clearAll();
        }
    };
    column1.addListener(SWT.Selection, sortListener);
    column2.addListener(SWT.Selection, sortListener);
    table.setSortColumn(column1);
    table.setSortDirection(SWT.UP);
    shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.cloud.test.longrun.PerformanceWithAPI.java

public static void main(String[] args) {

    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String host = "http://localhost";
    int numThreads = 1;

    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-h")) {
            host = "http://" + iter.next();
        }//from   ww  w .  ja va2s .  c  o m
        if (arg.equals("-t")) {
            numThreads = Integer.parseInt(iter.next());
        }
        if (arg.equals("-n")) {
            numVM = Integer.parseInt(iter.next());
        }
    }

    final String server = host + ":" + _apiPort + "/";
    final String developerServer = host + ":" + _developerPort + _apiUrl;

    s_logger.info("Starting test in " + numThreads + " thread(s). Each thread is launching " + numVM + " VMs");

    for (int i = 0; i < numThreads; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {

                    String username = null;
                    String singlePrivateIp = null;
                    String singlePublicIp = null;
                    Random ran = new Random();
                    username = Math.abs(ran.nextInt()) + "-user";

                    //Create User
                    User myUser = new User(username, username, server, developerServer);
                    try {
                        myUser.launchUser();
                        myUser.registerUser();
                    } catch (Exception e) {
                        s_logger.warn("Error code: ", e);
                    }

                    if (myUser.getUserId() != null) {
                        s_logger.info("User " + myUser.getUserName()
                                + " was created successfully, starting VM creation");
                        //create VMs for the user
                        for (int i = 0; i < numVM; i++) {
                            //Create a new VM, add it to the list of user's VMs
                            VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
                            myVM.deployVM(_zoneId, _serviceOfferingId, _templateId, myUser.getDeveloperServer(),
                                    myUser.getApiKey(), myUser.getSecretKey());
                            myUser.getVirtualMachines().add(myVM);
                            singlePrivateIp = myVM.getPrivateIp();

                            if (singlePrivateIp != null) {
                                s_logger.info(
                                        "VM with private Ip " + singlePrivateIp + " was successfully created");
                            } else {
                                s_logger.info("Problems with VM creation for a user" + myUser.getUserName());
                                break;
                            }

                            //get public IP address for the User            
                            myUser.retrievePublicIp(_zoneId);
                            singlePublicIp = myUser.getPublicIp().get(myUser.getPublicIp().size() - 1);
                            if (singlePublicIp != null) {
                                s_logger.info("Successfully got public Ip " + singlePublicIp + " for user "
                                        + myUser.getUserName());
                            } else {
                                s_logger.info("Problems with getting public Ip address for user"
                                        + myUser.getUserName());
                                break;
                            }

                            //create ForwardProxy rules for user's VMs
                            int responseCode = CreateForwardingRule(myUser, singlePrivateIp, singlePublicIp,
                                    "22", "22");
                            if (responseCode == 500)
                                break;
                        }

                        s_logger.info("Deployment successful..." + numVM
                                + " VMs were created. Waiting for 5 min before performance test");
                        Thread.sleep(300000L); // Wait 

                        //Start performance test for the user
                        s_logger.info("Starting performance test for Guest network that has "
                                + myUser.getPublicIp().size() + " public IP addresses");
                        for (int j = 0; j < myUser.getPublicIp().size(); j++) {
                            s_logger.info("Starting test for user which has "
                                    + myUser.getVirtualMachines().size() + " vms. Public IP for the user is "
                                    + myUser.getPublicIp().get(j) + " , number of retries is " + _retry
                                    + " , private IP address of the machine is"
                                    + myUser.getVirtualMachines().get(j).getPrivateIp());
                            guestNetwork myNetwork = new guestNetwork(myUser.getPublicIp().get(j), _retry);
                            myNetwork.setVirtualMachines(myUser.getVirtualMachines());
                            new Thread(myNetwork).start();
                        }

                    }
                } catch (Exception e) {
                    s_logger.error(e);
                }
            }
        }).start();

    }
}

From source file:TableSetDataEvent.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, new Listener() {
        public void handleEvent(Event e) {
            System.out.println(e);
            TableItem item = (TableItem) e.item;
            int index = table.indexOf(item);
            item.setText("Item " + data[index]);
        }/*w  ww.  j  a v a 2  s.co  m*/
    });
    int count = 0;
    Random random = new Random();
    while (count++ < 50) {
        int grow = 10;
        int[] newData = new int[data.length + grow];
        System.arraycopy(data, 0, newData, 0, data.length);
        int index = data.length;
        data = newData;
        for (int j = 0; j < grow; j++) {
            data[index++] = random.nextInt();
        }

        table.setItemCount(data.length);
        table.clearAll();
    }
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:Main.java

public static void main(String[] args) {
    Random r = new Random();

    // generate some random boolean values
    boolean[] booleans = new boolean[10];
    for (int i = 0; i < booleans.length; i++) {
        booleans[i] = r.nextBoolean();/*from   w ww .  j  ava 2s. co  m*/
    }

    for (boolean b : booleans) {
        System.out.print(b + ", ");
    }

    // generate a uniformly distributed int random numbers
    int[] integers = new int[10];
    for (int i = 0; i < integers.length; i++) {
        integers[i] = r.nextInt();
    }

    for (int i : integers) {
        System.out.print(i + ", ");
    }

    // generate a uniformly distributed float random numbers
    float[] floats = new float[10];
    for (int i = 0; i < floats.length; i++) {
        floats[i] = r.nextFloat();
    }

    for (float f : floats) {
        System.out.print(f + ", ");
    }

    // generate a Gaussian normally distributed random numbers
    double[] gaussians = new double[10];
    for (int i = 0; i < gaussians.length; i++) {
        gaussians[i] = r.nextGaussian();
    }

    for (double d : gaussians) {
        System.out.print(d + ", ");
    }
}

From source file:Snippet151.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, new Listener() {
        public void handleEvent(Event e) {
            TableItem item = (TableItem) e.item;
            int index = table.indexOf(item);
            item.setText("Item " + data[index]);
        }//from  ww  w . ja  v  a 2s.c  o  m
    });
    Thread thread = new Thread() {
        public void run() {
            int count = 0;
            Random random = new Random();
            while (count++ < 500) {
                if (table.isDisposed())
                    return;
                // add 10 random numbers to array and sort
                int grow = 10;
                int[] newData = new int[data.length + grow];
                System.arraycopy(data, 0, newData, 0, data.length);
                int index = data.length;
                data = newData;
                for (int j = 0; j < grow; j++) {
                    data[index++] = random.nextInt();
                }
                Arrays.sort(data);
                display.syncExec(new Runnable() {
                    public void run() {
                        if (table.isDisposed())
                            return;
                        table.setItemCount(data.length);
                        table.clearAll();
                    }
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed() || thread.isAlive()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}