Dúvida com resultado aleatório de array

10 respostas
magocebolinha

E ai pessoal

Bom para deixar minha duvida clara vou dar um exemplo:

import java.util.Scanner;

class Teste {
	
	public static void main (String args[]){
	
		Scanner scn = new Scanner (System.in);
		String [] RESPOSTAS= new String [5];
		String pergunta, resposta;
		
		System.out.println("Digite a pergunta");
		pergunta = scn.nextLine();
		
				
		RESPOSTAS [0] = "a";
		RESPOSTAS [1] = "b";
		RESPOSTAS [2] = "c";
		RESPOSTAS [3] = "d";
		RESPOSTAS [4] = "e";
		
		System.out.println("A resposta é: " + )   // <-- bom é aqui que eu tneho a duvida... sei que vou inserir o array  com algum metodo acredito..
	                        	                                          // não sei como fazer para gerar uma resposta aleatória.
	}
}

10 Respostas

thiago.correa

Você pode usar

Random r = new Random(System.currentTimeMillis());
    int max = 5; //o tamanho do seu vetor
    System.out.println(r.nextInt(max));

onde

ViniGodoy

Ou simplesmente use o construtor padrão da classe Random (que já faz o System.currentTimeMillis()).

int indiceAleatorio = new Random().nextInt(RESPOSTAS.length);
magocebolinha
magocebolinha:
import java.util.Scanner;

class Teste {
	
	public static void main (String args[]){
	
		Scanner scn = new Scanner (System.in);
		String [] RESPOSTAS= new String [5];
		String pergunta, resposta;
		
		System.out.println("Digite a pergunta");
		pergunta = scn.nextLine();
		
		
		
				
		RESPOSTAS [0] = "a";
		RESPOSTAS [1] = "b";
		RESPOSTAS [2] = "c";
		RESPOSTAS [3] = "d";
		RESPOSTAS [4] = "e";
		
		int respostaAleatoria = new Random().nextInt(RESPOSTAS.length);
		System.out.println(respostaAleatoria);
		
	}
}

agora gera o erro

---------- Capture Output ----------
> "C:\Program Files (x86)\Java\jdk1.6.0_18\bin\javac.exe" Teste.java
Teste.java:23: cannot find symbol
symbol  : class Random
location: class Teste
		int respostaAleatoria = new Random().nextInt(RESPOSTAS.length);
		                            ^
1 error
> Terminated with exit code 1.
thiago.correa

Fez o import da classe?!

discorpio

Boa tarde Magocebolinha.

Se bem entendi a sua dúvida, voce quer que o computador ofereça a resposta para uma possível pergunta do usuário.

Bom, se for isto mesmo, então é mais simples do que nunca.

Vamos utilizar a Classe “java.util.Random”, ao invés da classe Match e o seu método estático Random, assim

import java.util.scanner; 
import java.util.Random; // Importando a classe Random  
  
class Teste {   
       
    public static void main (String args[]){   
       
        Scanner scn = new Scanner (System.in)   
        String[] RESPOSTAS= new String[5];   
        String pergunta, resposta;   
           
        System.out.println("Digite a pergunta");   
        pergunta = scn.nextLine();   
           
                   
        RESPOSTAS [0] = "a"   
        RESPOSTAS [1] = "b"   
        RESPOSTAS [2] = "c"   
        RESPOSTAS [3] = "d"   
        RESPOSTAS [4] = "e" 

        // Acrescente este código:
        Random rd = new Random();
        int rand = 0;
        rand = rd.nextInt(5);  // O computador vai selecionar um número de 0 à 4        
           
        System.out.println("A resposta é: " + RESPOSTAS[rand] );

Espero que tenha ajudado.

magocebolinha

ah ok… mudei o import para java.util.* e deu certo… ok vou tentar

magocebolinha

interessante discorpio… mas como resposta ele retorna null… e da forma como o viny e o thiago propuseram, ele retorna o numero do índice e não o conteúdo…

W

Tenta esse

1. import java.util.Scanner; 2. 3. class Teste { 4. 5. public static void main (String args[]){ 6. 7. Scanner scn = new Scanner (System.in); 8. String [] RESPOSTAS= new String [5]; 9. String pergunta, resposta; 10. 11. System.out.println("Digite a pergunta"); 12. pergunta = scn.nextLine(); 13. 14. 15. 16. 17. RESPOSTAS [0] = "a"; 18. RESPOSTAS [1] = "b"; 19. RESPOSTAS [2] = "c"; 20. RESPOSTAS [3] = "d"; 21. RESPOSTAS [4] = "e"; 22. 23. int respostaAleatoria = new Random().nextInt(RESPOSTAS.length-1); 24. System.out.println(RESPOSTAS[respostaAleatoria]); 25. 26. } 27. }

pedroroxd
Bom, eu dei uma comentada ae... Eu faria assim:
import java.util.Random;
import java.util.Scanner;
   
 class Teste {  
       
     public static void main (String args[]){  
       
         Scanner scn = new Scanner (System.in);  
         String [] RESPOSTAS= new String[] {"a","b","c","d","e"};  //+ enxuto do que ficar citando...
         String pergunta, resposta; //PS.: Nao ta sendo usado pra nada....
           
         System.out.println("Digite a pergunta");  
         pergunta = scn.nextLine();  
           
           
         int posicao = new Random().nextInt(RESPOSTAS.length);  //gera um número de 0 a número de strings no RESPOSTAS
         System.out.println(RESPOSTAS[posicao]);  //printa
           
     }  
 }
pedroroxd

Se resolveu, só vai no primeiro tópico, e coloca [resolvido]
bons estudos, vlw

Criado 1 de abril de 2010
Ultima resposta 2 de abr. de 2010
Respostas 10
Participantes 6