Métodos de randomização em Java: Sorteio de valores

Veja neste artigo como construir uma aplicação para sorteio de valores em Java.

Neste artigo iremos aprender como utilizar os métodos de randomização em Java. Para melhor entendimento de tais assuntos nós iremos utilizar uma aplicação prática: A construção de um aplicativo que pode servir para sorteios de números.

Nota: Não deixe de conferir as formações profissionais em Java da DevMedia.

Criando as nossa Janelas / Forms

Nosso aplicativo será bem simples, como já dissemos anteriormente, possuindo apenas uma função básica de sorteio. Na função de sorteio o usuário poderá escolher um intervalo de valores (ex: 3 a 200) e a quantidade de números que ele deseja que sejam sorteados (Ex: o usuário pode querer sortear três números).

O primeiro passo para criação da nossa aplicação é desenvolver nossos formulários, então vamos começar com a tela principal que terá um menu de acesso a nossas funcionalidades. Optamos por usar o NetBeans para construção dos formulários e o Eclipse para codificação da nossa lógica de negócio, mas fique a vontade para usar outras IDE's de sua escolha.

Nosso formulário principal tem o nome FPrincipal (Listagem 1) e possui as seguintes características:

package br.com.dev.gui; import java.text.SimpleDateFormat; import java.util.Date; public class FPrincipal extends javax.swing.JFrame { /** Creates new form FPrincipal */ public FPrincipal() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Código Gerado ">//GEN-BEGIN:initComponents private void initComponents() { jtoolbar = new javax.swing.JToolBar(); jlabelDataHora = new javax.swing.JLabel(); jmenuBar = new javax.swing.JMenuBar(); jmenuPrincipal = new javax.swing.JMenu(); jmenuItemSorteio = new javax.swing.JMenuItem(); jmenuSair = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); jlabelDataHora.setText("Data e Hora atual: "); jtoolbar.add(jlabelDataHora); jlabelDataHora.getAccessibleContext().setAccessibleName("jLabelDataHora"); jmenuPrincipal.setText("Principal"); jmenuItemSorteio.setText("Sorteio"); jmenuPrincipal.add(jmenuItemSorteio); jmenuBar.add(jmenuPrincipal); jmenuSair.setText("Sair"); jmenuBar.add(jmenuSair); setJMenuBar(jmenuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtoolbar, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(254, Short.MAX_VALUE) .addComponent(jtoolbar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy H:m:s"); String dataHoraFormatada = sdf.format(new Date()); jlabelDataHora.setText(jlabelDataHora.getText() + " " + dataHoraFormatada); }//GEN-LAST:event_formWindowOpened /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FPrincipal().setVisible(true); } }); } // Declaração de variáveis - não modifique//GEN-BEGIN:variables private javax.swing.JLabel jlabelDataHora; private javax.swing.JMenuBar jmenuBar; private javax.swing.JMenuItem jmenuItemSorteio; private javax.swing.JMenu jmenuPrincipal; private javax.swing.JMenu jmenuSair; private javax.swing.JToolBar jtoolbar; // Fim da declaração de variáveis//GEN-END:variables }
Listagem 1. GUI Fprincipal

Perceba que nosso Fprincipal está no pacote br.com.dev.gui mas fique a vontade para definir outro pacote se desejar. Além disso, é importante salientar que toda construção do nosso formulário foi feita usando o netbeans, por isso os comentários padrões e indentação padrão da IDE, também é opcional, você pode construir seu formulário onde desejar.

Veja como ficou nossa interface gráfica em execução na Figura 1.

Figura 1. Fprincipal

Para quem tiver interesse em usar o NetBeans, pode usar o código do Fprincipal.form da Listagem 2.

<?xml version="1.0" encoding="UTF-8" ?> <Form version="1.3" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> <NonVisualComponents> <Menu class="javax.swing.JMenuBar" name="jmenuBar"> <SubComponents> <Menu class="javax.swing.JMenu" name="jmenuPrincipal"> <Properties> <Property name="text" type="java.lang.String" value="Principal"/> </Properties> <SubComponents> <MenuItem class="javax.swing.JMenuItem" name="jmenuItemSorteio"> <Properties> <Property name="text" type="java.lang.String" value="Sorteio"/> </Properties> </MenuItem> </SubComponents> </Menu> <Menu class="javax.swing.JMenu" name="jmenuSair"> <Properties> <Property name="text" type="java.lang.String" value="Sair"/> </Properties> </Menu> </SubComponents> </Menu> </NonVisualComponents> <Properties> <Property name="defaultCloseOperation" type="int" value="3"/> </Properties> <SyntheticProperties> <SyntheticProperty name="menuBar" type="java.lang.String" value="jmenuBar"/> <SyntheticProperty name="formSizePolicy" type="int" value="1"/> </SyntheticProperties> <Events> <EventHandler event="windowOpened" listener="java.awt.event.WindowListener" parameters="java.awt.event.WindowEvent" handler="formWindowOpened"/> </Events> <AuxValues> <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/> <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> </AuxValues> <Layout> <DimensionLayout dim="0"> <Group type="103" groupAlignment="0" attributes="0"> <Component id="jtoolbar" alignment="0" pref="400" max="32767" attributes="0"/> </Group> </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" alignment="0" attributes="0"> <EmptySpace pref="254" max="32767" attributes="0"/> <Component id="jtoolbar" min="-2" pref="25" max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> </Layout> <SubComponents> <Container class="javax.swing.JToolBar" name="jtoolbar"> <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBoxLayout"/> <SubComponents> <Component class="javax.swing.JLabel" name="jlabelDataHora"> <Properties> <Property name="text" type="java.lang.String" value="Data e Hora atual: "/> </Properties> <AccessibilityProperties> <Property name="AccessibleContext.accessibleName" type="java.lang.String" value="jLabelDataHora"/> </AccessibilityProperties> </Component> </SubComponents> </Container> </SubComponents> </Form>
Listagem 2. Fprincipal.form para NetBeans

Não entraremos em detalhes de funções básicas do Java pois não é foco deste artigo, iremos mostrar o desenvolvimento completo desta aplicação e dar foco na lógica utilizada para sorteio de valores.

Vamos realizar a construção do nosso formulário de sorteio de valores e por fim voltaremos ao Fprincipal para realizar a chamada a este formulário.

Formulário de Sorteio de valores – Fsorteio

Como já mencionamos anteriormente, neste formulário o usuário poderá escolher um intervalo de valores e a quantidade de valores a serem sorteados. Digamos, por exemplo, que o usuário deseje sortear três números entre 100 e 500, ou 1 número entre 1 e 100, nós possibilitaremos isso a ele.

Vale ressaltar que a prática que estamos adotando na construção deste software, colocando a lógica de negócio dentro do formulário, não é das melhores mas isso não é muito importante agora, já que nosso aplicativo é bem simples e não podemos desperdiçar muito tempo trabalhando com padrões de projeto complexos. Você, caro leitor, está aqui para aprender sobre a lógica de sorteio em Java e não sobre padrões de projeto. Observe a Listagem 3.

package br.com.dev.gui;    import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List;    import javax.swing.JOptionPane;       public class FSorteio extends javax.swing.JFrame {           /** Creates new form FSorteio */        public FSorteio() {              initComponents();        }           /**         * This method is called from within the constructor to initialize the form.         * WARNING: Do NOT modify this code. The content of this method is always         * regenerated by the Form Editor.         */        // <editor-fold defaultstate="collapsed"        // desc=" Código Gerado ">//GEN-BEGIN:initComponents        private void initComponents() {              jLabel1 = new javax.swing.JLabel();              jTextFieldQtd = new javax.swing.JTextField();              jLabel2 = new javax.swing.JLabel();              jTextFieldInicio = new javax.swing.JTextField();              jTextFieldFim = new javax.swing.JTextField();              jLabel3 = new javax.swing.JLabel();              jScrollPane1 = new javax.swing.JScrollPane();              jTextAreaResultado = new javax.swing.JTextArea();              jButtonSortear = new javax.swing.JButton();              jLabel4 = new javax.swing.JLabel();              jButtonCancelar = new javax.swing.JButton();                 jButtonCancelar.addActionListener(new ActionListener() {                        @Override                     public void actionPerformed(ActionEvent e) { sair();                        }              });                 jButtonSortear.addActionListener(new ActionListener() {                        @Override                     public void actionPerformed(ActionEvent e) {                      sortear(Integer.parseInt(jTextFieldQtd.getText()),   Integer.parseInt(jTextFieldInicio.getText()),                          Integer.parseInt(jTextFieldFim.getText()));                        }              });                 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);              setTitle("Sorteio de Valores");              jLabel1.setText("Quantidade");                 jTextFieldQtd.setText("1");                 jLabel2.setText("Intervalo");                 jTextFieldInicio.setText("1");                 jTextFieldFim.setText("100");                 jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);              jLabel3.setText("at\u00e9");                 jTextAreaResultado.setColumns(20);              jTextAreaResultado.setLineWrap(true);              jTextAreaResultado.setRows(5);              jScrollPane1.setViewportView(jTextAreaResultado);                 jButtonSortear.setText("Sortear");                 jLabel4.setText("Resultado:");                 jButtonCancelar.setText("Cancelar");                 javax.swing.GroupLayout layout = new javax.swing.GroupLayout( getContentPane());              getContentPane().setLayout(layout);              layout.setHorizontalGroup(layout                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                .addGroup(                   layout.createSequentialGroup()                      .addContainerGap()                      .addGroup(                       layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                         .addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT_SIZE,376, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(                          javax.swing.GroupLayout.Alignment.LEADING)                           .addComponent(jLabel1).addComponent( jTextFieldQtd,javax.swing.GroupLayout.PREFERRED_SIZE, 45,javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21,21) .addGroup(layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2).addGroup( layout.createSequentialGroup() .addComponent(jTextFieldInicio,javax.swing.GroupLayout .PREFERRED_SIZE,55,javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Label3,javax.swing.GroupLayout.PREFERRED_SIZE,33,javax .swing.GroupLayout.PREFERRED_SIZE) .addGap(3,3,3).addComponent(jTextFieldFim,javax .swing.GroupLayout.PREFERRED_SIZE,59,javax.swing.GroupLayout .PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addComponent(jButtonSortear) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonCancelar)).addComponent(jLabel4)).addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addContainerGap().addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldQtd,javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout .PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextFieldInicio,javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldFim,javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout .PREFERRED_SIZE)))).addGap(16, 16, 16).addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE).addComponent( jButtonSortear).addComponent(jButtonCancelar)).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED,28, Short.MAX_VALUE).addComponent(jLabel4).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED_SIZE,159, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap())); pack();        }// </editor-fold>//GEN-END:initComponents           /**         * @param args         *            the command line arguments         */        public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FSorteio().setVisible(true); }              });        }           public void sair() {              if (JOptionPane.showConfirmDialog(this, "Tem certeza que deseja sair ?", "Sair", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { this.dispose();              }        }           /*         * Sorteia uma quantidade X de valores dado o intervalo inicio e fim         * definidos nos argumentos do método sortear()         */        public void sortear(int quantidade, int inicio, int fim) {              jTextAreaResultado.setText("");              List<Integer> resultados = new ArrayList<Integer>();              Integer valorSorteado = 0;              for (int i = 0; i < quantidade; i++) {                     valorSorteado = randomizaIntervalo(inicio, fim);                        while (resultados.contains(valorSorteado)) { valorSorteado = randomizaIntervalo(inicio, fim);                     }                        jTextAreaResultado.append(Integer.toString(valorSorteado) + "\n");              }           }                 public int randomizaIntervalo(int inicio, int fim){              int valor = (int) (Math.random() * fim);              if (valor < inicio){                     valor = (inicio - valor) + valor;              }                             return valor;        }           // Declaração de variáveis - não modifique//GEN-BEGIN:variables        private javax.swing.JButton jButtonCancelar;        private javax.swing.JButton jButtonSortear;        private javax.swing.JLabel jLabel1;        private javax.swing.JLabel jLabel2;        private javax.swing.JLabel jLabel3;        private javax.swing.JLabel jLabel4;        private javax.swing.JScrollPane jScrollPane1;        private javax.swing.JTextArea jTextAreaResultado;        private javax.swing.JTextField jTextFieldFim;        private javax.swing.JTextField jTextFieldInicio;        private javax.swing.JTextField jTextFieldQtd;        // Fim da declaração de variáveis//GEN-END:variables    }
Listagem 3. Fsorteio.java

Para seguir o padrão, segue na Listagem 4 nosso Fsorteio.form para quem desejar abrir o design no NetBeans.

<?xml version="1.0" encoding="UTF-8" ?> <Form version="1.3" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> <Properties> <Property name="defaultCloseOperation" type="int" value="3"/> <Property name="title" type="java.lang.String" value="Sorteio de Valores"/> </Properties> <SyntheticProperties> <SyntheticProperty name="formSizePolicy" type="int" value="1"/> </SyntheticProperties> <AuxValues> <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/> <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> </AuxValues> <Layout> <DimensionLayout dim="0"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" attributes="0"> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> <Component id="jScrollPane1" alignment="0" pref="376" max="32767" attributes="0"/> <Group type="102" attributes="0"> <Group type="103" groupAlignment="0" attributes="0"> <Component id="jLabel1" min="-2" max="-2" attributes="1"/> <Component id="jTextFieldQtd" min="-2" pref="45" max="-2" attributes="1"/> </Group> <EmptySpace min="-2" pref="21" max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/> <Group type="102" alignment="0" attributes="0"> <Component id="jTextFieldInicio" min="-2" pref="55" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="jLabel3" min="-2" pref="33" max="-2" attributes="0"/> <EmptySpace min="-2" pref="3" max="-2" attributes="0"/> <Component id="jTextFieldFim" min="-2" pref="59" max="-2" attributes="0"/> </Group> </Group> </Group> <Group type="102" alignment="0" attributes="0"> <Component id="jButtonSortear" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="jButtonCancelar" min="-2" max="-2" attributes="0"/> </Group> <Component id="jLabel4" alignment="0" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" alignment="0" attributes="0"> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" attributes="0"> <Component id="jLabel1" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="jTextFieldQtd" min="-2" max="-2" attributes="0"/> </Group> <Group type="102" attributes="0"> <Component id="jLabel2" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="jTextFieldInicio" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="jTextFieldFim" alignment="3" min="-2" max="-2" attributes="0"/> </Group> </Group> </Group> <EmptySpace min="-2" pref="16" max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="jButtonSortear" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="jButtonCancelar" alignment="3" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace pref="28" max="32767" attributes="0"/> <Component id="jLabel4" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="jScrollPane1" min="-2" pref="159" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> </Layout> <SubComponents> <Component class="javax.swing.JLabel" name="jLabel1"> <Properties> <Property name="text" type="java.lang.String" value="Quantidade"/> </Properties> </Component> <Component class="javax.swing.JTextField" name="jTextFieldQtd"> <Properties> <Property name="text" type="java.lang.String" value="1"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel2"> <Properties> <Property name="text" type="java.lang.String" value="Intervalo"/> </Properties> </Component> <Component class="javax.swing.JTextField" name="jTextFieldInicio"> <Properties> <Property name="text" type="java.lang.String" value="1"/> </Properties> </Component> <Component class="javax.swing.JTextField" name="jTextFieldFim"> <Properties> <Property name="text" type="java.lang.String" value="100"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel3"> <Properties> <Property name="horizontalAlignment" type="int" value="0"/> <Property name="text" type="java.lang.String" value="até"/> </Properties> </Component> <Container class="javax.swing.JScrollPane" name="jScrollPane1"> <AuxValues> <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/> </AuxValues> <Layout class="org.netbeans.modules.form.compat2.layouts.support .JScrollPaneSupportLayout"/> <SubComponents> <Component class="javax.swing.JTextArea" name="jTextAreaResultado"> <Properties> <Property name="columns" type="int" value="20"/> <Property name="lineWrap" type="boolean" value="true"/> <Property name="rows" type="int" value="5"/> </Properties> </Component> </SubComponents> </Container> <Component class="javax.swing.JButton" name="jButtonSortear"> <Properties> <Property name="text" type="java.lang.String" value="Sortear"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonSortearActionPerformed"/> </Events> </Component> <Component class="javax.swing.JLabel" name="jLabel4"> <Properties> <Property name="text" type="java.lang.String" value="Resultado:"/> </Properties> </Component> <Component class="javax.swing.JButton" name="jButtonCancelar"> <Properties> <Property name="text" type="java.lang.String" value="Cancelar"/> </Properties> </Component> </SubComponents> </Form>
Listagem 4. Fsorteio.form

Todo o código postado acima servirá perfeitamente para você criar o mesmo projeto idêntico no seu ambiente, mas vamos focar no método sortear() e randomizaIntervalo() mostrados na Listagem 3.

O método sortear() faz um loop de acordo com a quantidade de números que o usuário deseja sortear, dentro desse loop um valor qualquer é sorteado e logo em seguida é checado se este valor já existe no ArrayList que chamamos de result. Enquanto for sorteado um valor que já existe o laço while continuará sorteando outros até que seja encontrado um novo e adicionado ao ArrayList.

Mas o importante mesmo é entendermos o método randomizaIntervalo() que faz o sorteio propriamente dito. O método Math.random() retorna um valor que vai de 0 até 1, ou seja, 0.1, 0.3, 0.9, 0.34 e etc. Como queremos que intervalo vá até 100 basta multiplicarmos o valor retornado pelo Math.random() por 100, ou seja, se o Math.random() retornar 1 teremos: 1x100 = 100.

Usamos um cast para inteiro pois o valor do Math.random() multiplicado pela variável 'fim' deve ser inteiro e não decimal, assim não teremos números como: 99.10, 30.12 e etc. Mas além do limite máximo (que no nosso exemplo é 100) definimos também um limite mínimo, então para garantir que o número sorteado nunca seja menor que o limite mínimo, nós checamos se o valor sorteado é menor que a variável inicio, e caso isso seja verdade apenas adicionamos a diferença ao valor sorteado.

O objetivo deste artigo foi demonstrar como construir um aplicativo do zero para sorteio de valores em Java, desde a construção do formulário até a explicação da lógica envolvida no sorteio.

Ebook exclusivo
Dê um upgrade no início da sua jornada. Crie sua conta grátis e baixe o e-book

Artigos relacionados