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(int bound) 

Source Link

Document

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Usage

From source file:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    StyledDocument doc = new DefaultStyledDocument();
    JTextPane textPane = new JTextPane(doc);
    textPane.setText("this is a test.");

    Random random = new Random();
    for (int i = 0; i < textPane.getDocument().getLength(); i++) {
        SimpleAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setForeground(set,
                new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        StyleConstants.setFontSize(set, random.nextInt(12) + 12);
        StyleConstants.setBold(set, random.nextBoolean());
        StyleConstants.setItalic(set, random.nextBoolean());
        StyleConstants.setUnderline(set, random.nextBoolean());

        doc.setCharacterAttributes(i, 1, set, true);
    }//from  w w w .j  av  a 2 s .  co  m

    frame.add(new JScrollPane(textPane));
    frame.setSize(500, 400);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Button Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JButton button1 = new JButton("Select Me");
    final JButton button2 = new JButton("No Select Me");
    final Random random = new Random();

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JButton button = (JButton) actionEvent.getSource();
            int red = random.nextInt(255);
            int green = random.nextInt(255);
            int blue = random.nextInt(255);
            button.setBackground(new Color(red, green, blue));
        }/*  w ww .  j a  v a2 s. c om*/
    };

    PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
            String property = propertyChangeEvent.getPropertyName();
            if ("background".equals(property)) {
                button2.setBackground((Color) propertyChangeEvent.getNewValue());
            }
        }
    };

    button1.addActionListener(actionListener);
    button1.addPropertyChangeListener(propertyChangeListener);
    button2.addActionListener(actionListener);

    frame.add(button1, BorderLayout.NORTH);
    frame.add(button2, BorderLayout.SOUTH);
    frame.setSize(300, 100);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    Random RND = new Random();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<String>> results = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
    }// w ww .j a  v a 2 s .  c  om
    es.shutdown();
    while (!results.isEmpty()) {
        Iterator<Future<String>> i = results.iterator();
        while (i.hasNext()) {
            Future<String> f = i.next();
            if (f.isDone()) {
                System.out.println(f.get());
                i.remove();
            }
        }
    }
}

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

public static void main(String[] args) throws Exception {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 375");
    shell.setLayout(new GridLayout(1, false));

    final StringBuilder sb = new StringBuilder();
    final Random random = new Random(2546);
    for (int i = 0; i < 200; i++) {
        sb.append("Very very long text about ").append(random.nextInt(2000)).append("\t");
        if (i % 10 == 0) {
            sb.append("\n");
        }//from   w w w  .ja v  a  2  s. c  o m
    }

    // H SCROLL
    final Label lbl1 = new Label(shell, SWT.NONE);
    lbl1.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl1.setText("Horizontal Scroll");

    final StyledText txt1 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL);
    txt1.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
    txt1.setText(sb.toString());
    txt1.setMouseNavigatorEnabled(true);

    // V_SCROLL
    final Label lbl2 = new Label(shell, SWT.NONE);
    lbl2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl2.setText("Vertical Scroll");

    final StyledText txt2 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    txt2.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
    txt2.setText(sb.toString());
    txt2.setMouseNavigatorEnabled(true);

    // H SCROLL & V_SCROLL
    final Label lbl3 = new Label(shell, SWT.NONE);
    lbl3.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl3.setText("Horizontal and Vertical Scroll");

    final StyledText txt3 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    txt3.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));

    txt3.setText(sb.toString());
    txt3.setMouseNavigatorEnabled(true);

    final Button enableDisableButton = new Button(shell, SWT.PUSH);
    enableDisableButton.setLayoutData(new GridData(GridData.END, GridData.FILL, true, false));
    enableDisableButton.setText("Disable Mouse Navigation");
    enableDisableButton.addListener(SWT.Selection, e -> {
        if (txt3.getMouseNavigatorEnabled()) {
            enableDisableButton.setText("Enable Mouse Navigation");
        } else {
            enableDisableButton.setText("Disable Mouse Navigation");
        }
        txt3.setMouseNavigatorEnabled(!txt3.getMouseNavigatorEnabled());
    });

    // Disabled Scroll at start
    final Label lbl4 = new Label(shell, SWT.NONE);
    lbl4.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl4.setText("No scroll at start");

    final StyledText txt4 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
    final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, true);
    gd.minimumHeight = 100;
    txt4.setLayoutData(gd);

    txt4.setText("Disabled scroll");
    txt4.setMouseNavigatorEnabled(true);

    // Disabled Scroll
    final Label lbl5 = new Label(shell, SWT.NONE);
    lbl5.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl5.setText("No scroll");

    final StyledText txt5 = new StyledText(shell, SWT.MULTI | SWT.BORDER);
    final GridData gd5 = new GridData(GridData.FILL, GridData.FILL, true, true);
    gd5.minimumHeight = 100;
    txt5.setLayoutData(gd5);

    txt5.setText("No scroll");
    txt5.setMouseNavigatorEnabled(true);

    shell.setSize(800, 600);
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

    display.dispose();
}

From source file:PropertyChangeListenerDemo.java

public static void main(String args[]) {
    Runnable runner = new Runnable() {
        public void run() {
            JFrame frame = new JFrame("Button Sample");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final JButton button1 = new JButton("Select Me");
            final JButton button2 = new JButton("No Select Me");
            final Random random = new Random();
            // Define ActionListener
            ActionListener actionListener = new ActionListener() {
                public void actionPerformed(ActionEvent actionEvent) {
                    JButton button = (JButton) actionEvent.getSource();
                    int red = random.nextInt(255);
                    int green = random.nextInt(255);
                    int blue = random.nextInt(255);
                    button.setBackground(new Color(red, green, blue));
                }//w w w  .j  a v  a  2 s .co  m
            };
            // Define PropertyChangeListener
            PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
                    String property = propertyChangeEvent.getPropertyName();
                    if ("background".equals(property)) {
                        button2.setBackground((Color) propertyChangeEvent.getNewValue());
                    }
                }
            };
            button1.addActionListener(actionListener);
            button1.addPropertyChangeListener(propertyChangeListener);
            button2.addActionListener(actionListener);
            frame.add(button1, BorderLayout.NORTH);
            frame.add(button2, BorderLayout.SOUTH);
            frame.setSize(300, 100);
            frame.setVisible(true);
        }
    };
    EventQueue.invokeLater(runner);
}

From source file:dhtaccess.benchmark.LatencyMeasure.java

public static void main(String[] args) {
    boolean details = false;
    int repeats = DEFAULT_REPEATS;
    boolean doPut = true;

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("d", "details", false, "requests secret hash and TTL");
    options.addOption("r", "repeats", true, "number of requests");
    options.addOption("n", "no-put", false, "does not put");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from w  w  w  . j  ava 2  s.  c o m*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    if (cmd.hasOption('d')) {
        details = true;
    }
    optVal = cmd.getOptionValue('r');
    if (optVal != null) {
        repeats = Integer.parseInt(optVal);
    }
    if (cmd.hasOption('n')) {
        doPut = false;
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 1) {
        usage(COMMAND);
        System.exit(1);
    }

    // prepare for RPC
    int numAccessor = args.length;
    DHTAccessor[] accessorArray = new DHTAccessor[numAccessor];
    try {
        for (int i = 0; i < numAccessor; i++) {
            accessorArray[i] = new DHTAccessor(args[i]);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // generate key prefix
    Random rnd = new Random(System.currentTimeMillis());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < KEY_PREFIX_LENGTH; i++) {
        sb.append((char) ('a' + rnd.nextInt(26)));
    }
    String keyPrefix = sb.toString();
    String valuePrefix = VALUE_PREFIX;

    // benchmarking
    System.out.println("Repeats " + repeats + " times.");

    if (doPut) {
        System.out.println("Putting: " + keyPrefix + "<number>");

        for (int i = 0; i < repeats; i++) {
            byte[] key = null, value = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
                value = (valuePrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            acc.put(key, value, TTL);
        }
    }

    System.out.println("Benchmarking by getting.");

    int count = 0;
    long startTime = System.currentTimeMillis();

    if (details) {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<DetailedGetResult> valueSet = acc.getDetails(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    } else {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<byte[]> valueSet = acc.get(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    }

    System.out.println(System.currentTimeMillis() - startTime + " msec.");
    System.out.println("Rate of successful gets: " + count + " / " + repeats);
}

From source file:com.offbynull.peernetic.debug.visualizer.App.java

public static void main(String[] args) throws Throwable {
    Random random = new Random();
    Visualizer<Integer> visualizer = new JGraphXVisualizer<>();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Recorder<Integer> recorder = new XStreamRecorder(baos);

    visualizer.visualize(recorder, null);

    visualizer.step("Adding nodes 1 and 2", new AddNodeCommand<>(1),
            new ChangeNodeCommand(1, null, new Point(random.nextInt(400), random.nextInt(400)), Color.RED),
            new AddNodeCommand<>(2),
            new ChangeNodeCommand(2, null, new Point(random.nextInt(400), random.nextInt(400)), Color.BLUE));
    Thread.sleep(500);/*from w  ww . ja  va2 s . c  o  m*/

    visualizer.step("Adding nodes 3 and 4", new AddNodeCommand<>(3),
            new ChangeNodeCommand(3, null, new Point(random.nextInt(400), random.nextInt(400)), Color.ORANGE),
            new AddNodeCommand<>(4),
            new ChangeNodeCommand(4, null, new Point(random.nextInt(400), random.nextInt(400)), Color.PINK));
    Thread.sleep(500);

    visualizer.step("Connecting 1/2/3 to 4", new AddEdgeCommand<>(1, 4), new AddEdgeCommand<>(2, 4),
            new AddEdgeCommand<>(3, 4));
    Thread.sleep(500);

    visualizer.step("Adding trigger to 4 when no more edges",
            new TriggerOnLingeringNodeCommand(4, new RemoveNodeCommand<>(4)));
    Thread.sleep(500);

    visualizer.step("Removing connections from 1 and 2", new RemoveEdgeCommand<>(1, 4),
            new RemoveEdgeCommand<>(2, 4));
    Thread.sleep(500);

    visualizer.step("Removing connections from 3", new RemoveEdgeCommand<>(3, 4));
    Thread.sleep(500);

    recorder.close();

    Thread.sleep(2000);

    JGraphXVisualizer<Integer> visualizer2 = new JGraphXVisualizer<>();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    Player<Integer> player = new XStreamPlayer<>(bais);

    visualizer2.visualize();

    player.play(visualizer2);

}

From source file:backup.store.ExternalExtendedBlockSort.java

public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    Path dir = new Path("file:///home/apm/Development/git-projects/hdfs-backup/hdfs-backup-core/tmp");
    dir.getFileSystem(conf).delete(dir, true);
    long start = System.nanoTime();
    try (ExternalExtendedBlockSort<LongWritable> sort = new ExternalExtendedBlockSort<>(conf, dir,
            LongWritable.class)) {
        Random random = new Random();
        for (int bp = 0; bp < 1; bp++) {
            String bpid = UUID.randomUUID().toString();
            for (int i = 0; i < 10000000; i++) {
                // for (int i = 0; i < 10; i++) {
                long genstamp = random.nextInt(20000);
                long blockId = random.nextLong();
                ExtendedBlock extendedBlock = new ExtendedBlock(bpid, blockId,
                        random.nextInt(Integer.MAX_VALUE), genstamp);
                sort.add(extendedBlock, new LongWritable(blockId));
            }/*from  w  w  w.  j  ava2 s.c  om*/
        }
        System.out.println("finished");
        sort.finished();
        System.out.println("interate");
        for (String blockPoolId : sort.getBlockPoolIds()) {
            ExtendedBlockEnum<LongWritable> blockEnum = sort.getBlockEnum(blockPoolId);
            ExtendedBlock block;
            long l = 0;
            while ((block = blockEnum.next()) != null) {
                // System.out.println(block);
                long blockId = block.getBlockId();
                l += blockId;
                LongWritable currentValue = blockEnum.currentValue();
                if (currentValue.get() != blockId) {
                    System.err.println("Error " + blockId);
                }
            }
            System.out.println(l);
        }
    }
    long end = System.nanoTime();
    System.out.println("Time [" + (end - start) / 1000000.0 + " ms]");
}

From source file:hyperloglog.tools.HyperLogLogCLI.java

public static void main(String[] args) {
    Options options = new Options();
    addOptions(options);/*from www.  j  a  va 2s .  c o  m*/

    CommandLineParser parser = new BasicParser();
    CommandLine cli = null;
    long n = 0;
    long seed = 123;
    EncodingType enc = EncodingType.SPARSE;
    int p = 14;
    int hb = 64;
    boolean bitPack = true;
    boolean noBias = true;
    int unique = -1;
    String filePath = null;
    BufferedReader br = null;
    String outFile = null;
    String inFile = null;
    FileOutputStream fos = null;
    DataOutputStream out = null;
    FileInputStream fis = null;
    DataInputStream in = null;
    try {
        cli = parser.parse(options, args);

        if (!(cli.hasOption('n') || cli.hasOption('f') || cli.hasOption('d'))) {
            System.out.println("Example usage: hll -n 1000 " + "<OR> hll -f /tmp/input.txt "
                    + "<OR> hll -d -i /tmp/out.hll");
            usage(options);
            return;
        }

        if (cli.hasOption('n')) {
            n = Long.parseLong(cli.getOptionValue('n'));
        }

        if (cli.hasOption('e')) {
            String value = cli.getOptionValue('e');
            if (value.equals(EncodingType.DENSE.name())) {
                enc = EncodingType.DENSE;
            }
        }

        if (cli.hasOption('p')) {
            p = Integer.parseInt(cli.getOptionValue('p'));
            if (p < 4 && p > 16) {
                System.out.println("Warning! Out-of-range value specified for p. Using to p=14.");
                p = 14;
            }
        }

        if (cli.hasOption('h')) {
            hb = Integer.parseInt(cli.getOptionValue('h'));
        }

        if (cli.hasOption('c')) {
            noBias = Boolean.parseBoolean(cli.getOptionValue('c'));
        }

        if (cli.hasOption('b')) {
            bitPack = Boolean.parseBoolean(cli.getOptionValue('b'));
        }

        if (cli.hasOption('f')) {
            filePath = cli.getOptionValue('f');
            br = new BufferedReader(new FileReader(new File(filePath)));
        }

        if (filePath != null && cli.hasOption('n')) {
            System.out.println("'-f' (input file) specified. Ignoring -n.");
        }

        if (cli.hasOption('s')) {
            if (cli.hasOption('o')) {
                outFile = cli.getOptionValue('o');
                fos = new FileOutputStream(new File(outFile));
                out = new DataOutputStream(fos);
            } else {
                System.err.println("Specify output file. Example usage: hll -s -o /tmp/out.hll");
                usage(options);
                return;
            }
        }

        if (cli.hasOption('d')) {
            if (cli.hasOption('i')) {
                inFile = cli.getOptionValue('i');
                fis = new FileInputStream(new File(inFile));
                in = new DataInputStream(fis);
            } else {
                System.err.println("Specify input file. Example usage: hll -d -i /tmp/in.hll");
                usage(options);
                return;
            }
        }

        // return after deserialization
        if (fis != null && in != null) {
            long start = System.currentTimeMillis();
            HyperLogLog deserializedHLL = HyperLogLogUtils.deserializeHLL(in);
            long end = System.currentTimeMillis();
            System.out.println(deserializedHLL.toString());
            System.out.println("Count after deserialization: " + deserializedHLL.count());
            System.out.println("Deserialization time: " + (end - start) + " ms");
            return;
        }

        // construct hll and serialize it if required
        HyperLogLog hll = HyperLogLog.builder().enableBitPacking(bitPack).enableNoBias(noBias).setEncoding(enc)
                .setNumHashBits(hb).setNumRegisterIndexBits(p).build();

        if (br != null) {
            Set<String> hashset = new HashSet<String>();
            String line;
            while ((line = br.readLine()) != null) {
                hll.addString(line);
                hashset.add(line);
            }
            n = hashset.size();
        } else {
            Random rand = new Random(seed);
            for (int i = 0; i < n; i++) {
                if (unique < 0) {
                    hll.addLong(rand.nextLong());
                } else {
                    int val = rand.nextInt(unique);
                    hll.addLong(val);
                }
            }
        }

        long estCount = hll.count();
        System.out.println("Actual count: " + n);
        System.out.println(hll.toString());
        System.out.println("Relative error: " + HyperLogLogUtils.getRelativeError(n, estCount) + "%");
        if (fos != null && out != null) {
            long start = System.currentTimeMillis();
            HyperLogLogUtils.serializeHLL(out, hll);
            long end = System.currentTimeMillis();
            System.out.println("Serialized hyperloglog to " + outFile);
            System.out.println("Serialized size: " + out.size() + " bytes");
            System.out.println("Serialization time: " + (end - start) + " ms");
            out.close();
        }
    } catch (ParseException e) {
        System.err.println("Invalid parameter.");
        usage(options);
    } catch (NumberFormatException e) {
        System.err.println("Invalid type for parameter.");
        usage(options);
    } catch (FileNotFoundException e) {
        System.err.println("Specified file not found.");
        usage(options);
    } catch (IOException e) {
        System.err.println("Exception occured while reading file.");
        usage(options);
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    Random randomNumbers = new Random(); // random number generator

    int frequency1 = 0; // count of 1s rolled
    int frequency2 = 0; // count of 2s rolled
    int frequency3 = 0; // count of 3s rolled
    int frequency4 = 0; // count of 4s rolled
    int frequency5 = 0; // count of 5s rolled
    int frequency6 = 0; // count of 6s rolled

    int face; // stores most recently rolled value

    // summarize results of 6000 rolls of a die
    for (int roll = 1; roll <= 6000; roll++) {
        face = 1 + randomNumbers.nextInt(6); // number from 1 to 6

        // determine roll value 1-6 and increment appropriate counter
        switch (face) {
        case 1:/* w  w w.jav a2  s . co m*/
            ++frequency1; // increment the 1s counter
            break;
        case 2:
            ++frequency2; // increment the 2s counter
            break;
        case 3:
            ++frequency3; // increment the 3s counter
            break;
        case 4:
            ++frequency4; // increment the 4s counter
            break;
        case 5:
            ++frequency5; // increment the 5s counter
            break;
        case 6:
            ++frequency6; // increment the 6s counter
            break; // optional at end of switch
        }
    }

    System.out.println("Face\tFrequency"); // output headers
    System.out.printf("1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n", frequency1, frequency2, frequency3,
            frequency4, frequency5, frequency6);
}