Go through a vector and compare a random number

0

When it enters the vector and the number is not in the array it shows me "I do not win a match" the 12 times the vector travels. I want it to only show me once, I do not win and I keep doing the rest of the instructions

int azar = (int) (Math.random() * 38 + 0);

int[] veinticincos = {25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36};

 for (int i = 0; i <= 11; i++) {
     if (azar == veinticincos[i]) {
         System.out.println("Usted gano y su numero es" + azar);           
     } else {
         System.out.println("no gano parcero");           
     }
 }
    
asked by Rigoberto Oviedo Bolaños 14.10.2017 в 14:20
source

3 answers

2

Try this.

String mensaje = "no gano parcero";
for (int i = 0; i <= 11; i++) {
    if (azar == veinticincos[i]) {
        mensaje = "Usted gano y su numero es" + azar;
        break;           
    }
}
System.out.println(mensaje);    
    
answered by 14.10.2017 в 15:18
0

Good morning,

Try transforming your array into a list and using the contains function to check if the generated number is in the list. The code would look like this:

int azar = (int) (Math.random() * 38 + 0);

        Integer[] veinticincos = {25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36};

        List<Integer> lista = Arrays.asList(veinticincos);

        if (lista.contains(azar)) {
                 System.out.println("Usted gano y su numero es" + azar);           
        } else {
                 System.out.println("no gano parcero");           
        }

Integer "is an object for values of type int". It is necessary since the lists can not be primitive.

I hope I have helped you.

Greetings.

    
answered by 15.10.2017 в 12:50
0

You can also try this

int azar = (int) (Math.random() * 38 + 0);

int[] veinticincos = {25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36};


int a=0;

 for (int i = 0; i <= 11; i++) {

     if (azar == veinticincos[i]) {
         System.out.println("Usted gano y su numero es" + azar); 
         a=1;          
     } 
 }

 if(a==0){

 System.out.println("no gano parcero"); 

 }
    
answered by 15.10.2017 в 04:13