Como gero um numero randomico?

10 respostas
T

Ola estou tentando assim:

x = 10 + (int) ( Math.random() * 99 );

onde o x eh: int x;

porem da o erro:

cannot find symbol
symbol: variable Random

como, gero um numero randomico?

[]s

10 Respostas

G

dê uma olhada nesse artigo:

http://www.guj.com.br/java.artigo.17.1.guj

:wink:

S

cara usei o mesmo exemplo que vc postou e ele esta gerando blz! verifica se vc não escreveu random() com o R maiusculo!

vc colocou na hora que postou o erro o R maiusculo! as vezes pode ser isto!

[]s Victor …

T

amigos, eis o que me aconteceu!

tentei com o R maiusculo e continua dando erro…

agora tentei do jeito que o amigo disse, e funcionou! porem da outro erro!

n = new int[10];
           
            x = random.nextInt(99);

                  
            n[1] = random.nextInt(10);
            n[3] = random.nextInt(10);
            n[5] = random.nextInt(10);
            n[7] = random.nextInt(10);
            n[9] = random.nextInt(10);
                
            n[2] = random.nextInt(10);
            n[4] = random.nextInt(10);
            n[6] = random.nextInt(10);
            n[8] = random.nextInt(10);
            
            sum1 = n[1] + n[3] + n[5] + n[7] + n[9];
            sum2 = n[2] + n[4] + n[6] + n[8];

            s = x - sum1;
            n[10] = s - sum2;

Todas as variaveis criadas como int

nesta parte

s = x - sum1;

n[10] = s - sum2;

da o erro:

incompatible types
found: int
required: javax.microedition.lcdui.Displayable

bem… o que esta acontecendo agora?^

um pergunta

x = random.nextInt(99);

pode gerar qualquer numero de 0 a 99, porem queria que fosse de 10 a 99, como faco?

T

ah… o n eh um vetor de int

[]s

J
da pra fazer assim
int x = random.nextInt(99);

while (x<10) {
 x = random.nextInt(99);
}

tenta ai

[]'s
T

Valeu galera… funcionou perfeitamente, agora não estou conseguindo transformar o n[i] (inteiro) pra string… :frowning:

[]s

J
String string = String.valueOf( n[i] );

assim da certo!!

[]'s

T

valeu, funcinou, porem deu outro erro :smiley:

/*
 * HelloMIDlet.java
 *
 * Created on 2 de Março de 2005, 15:55
 */

package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Random;

/**
 * An example MIDlet with simple "Hello" text and an Exit command.
 * Refer to the startApp, pauseApp, and destroyApp
 * methods so see how each handles the requested transition.
 *
 * @author  Felipe
 * @version
 */
public class HelloMIDlet extends MIDlet implements CommandListener {
    
    private Command exitCommand, gerarCommand; // The exit command
    private Display display;    // The display for this MIDlet
    int n[];
    Random random = new Random(19857);
    int sum1, sum2;
    String strchave;
            
           
    public HelloMIDlet() {
        display = Display.getDisplay(this);
        exitCommand = new Command("Sair", Command.SCREEN, 2);
        gerarCommand = new Command("Gerar", Command.SCREEN, 3);
    }
    
    /**
     * Start up the Hello MIDlet by creating the TextBox and associating
     * the exit command and listener.
     */
    public void startApp() {
        TextBox t = new TextBox("Gerador de Seriais ", "String de Teste", 256, 0);
        
        t.addCommand(exitCommand);
        t.addCommand(gerarCommand);
        t.setCommandListener(this);
        
        display.setCurrent(t);
    }
    
    /**
     * Pause is a no-op since there are no background activities or
     * record stores that need to be closed.
     */
    public void pauseApp() {
    }
    
    /**
     * Destroy must cleanup everything not handled by the garbage collector.
     * In this case there is nothing to cleanup.
     */
    public void destroyApp(boolean unconditional) {
    }
    
    /*
     * Respond to commands, including exit
     * On the exit command, cleanup and notify that the MIDlet has been destroyed.
     */
    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }

        if (c == gerarCommand) {
            n = new int[10];
                
            n[1] = random.nextInt(10);
            n[3] = random.nextInt(10);
            n[5] = random.nextInt(10);
            n[7] = random.nextInt(10);
            n[9] = random.nextInt(10);
                
            n[2] = random.nextInt(10);
            n[4] = random.nextInt(10);
            n[6] = random.nextInt(10);
            n[8] = random.nextInt(10);
            
            sum1 = n[1] + n[3] + n[5] + n[7] + n[9];
            sum2 = n[2] + n[4] + n[6] + n[8];

            int x = random.nextInt(99); 

            while (x<10) { 
                x = random.nextInt(99); 
            } 
            
           int y = x - sum1;
           
           n[10] = y - sum2;
           
           Alert alert = new Alert("Chave de Liberacao");
           alert.setTimeout(Alert.FOREVER);
           
           strchave = 'C' + String.valueOf(n[1]) + String.valueOf(n[2]) +
           String.valueOf(n[3]) + String.valueOf(n[4]) + String.valueOf(n[5]) + String.valueOf(n[6])
           + String.valueOf(n[7]) + String.valueOf(n[8]) + String.valueOf(n[9]) + String.valueOf(n[10])
           + String.valueOf(x);
           
           alert.setString(strchave);
                   
        }
    }
    
}

Erro:

java.lang.ArrayIndexOutOfBoundsException at hello.HelloMIDlet.commandAction(+295) at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(+282) at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(+10) at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(+68) at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(+47) at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(+250) Execution completed.

Cara, desculpe, devo estar enchendo o saco, mas nao estou conseguindo… :frowning:

[]s

J

hee nem esquenta no comeco eh foda mesmo

entao tem essa linha q vc faz isso :

  • String.valueOf(n[10])

o n eh um vetor de no maximo 10!!!
entao ele vai da posicao 0 ate a posicao 9

na linha q eu mostrei acima vc ta tentando acessar a posicao 10…que nao existe!!
é isso

[]'s!!!

se vc tiver icq meu numero eh 26756914

falow

T

Olá pessoal entro atrasado na conversa mas só queria acrescentar uma coisa
O método

Só existe em dispositivos que implementam CLDC 1.1 e não 1.0.
Por exemplo os celulares da siemens só os da série 60 em diante
Ok
ps.: para ver uma lista e qual a versão acesse

http://developers.sun.com/techtopics/mobility/device/device

Criado 2 de março de 2005
Ultima resposta 7 de mar. de 2005
Respostas 10
Participantes 5