samedi 13 janvier 2018

I have to write a program in java , and it searches to generate 20 random numbers from 1-6

And I have to check if 2 or more numbers one after other are equal.
for example: 523(44)62(1111)14563(222)5
this is my code but sometimes it shows me this error:
java.lang.ArrayIndexOutOfBoundsException: 20

import java.util.Random;

public class Ushtr3 { public static void main(String [] args){

    int[] a = new int[20];
    Random nr = new Random();

    System.out.println("Program:");

    for(int i=0; i<a.length; i++){
        a[i]=1+nr.nextInt(6);
    }

    for(int i=0; i<a.length; i++){
        System.out.print(a[i]);
    }

    System.out.print("\n");

    for(int i=0; i<a.length; i++){

        while(i!=19){
            if((a[i]==a[i+1]) && (a[i]==a[i+2]) && (a[i]==a[i+3]) && (a[i]==a[i+4])){
                System.out.print("("+a[i]+""+a[i+1]+""+a[i+2]+""+a[i+3]+""+a[i+4]+")");
                i++;
                break;
            }
            else if((a[i]==a[i+1]) && (a[i]==a[i+2]) && (a[i]==a[i+3])){
                System.out.print("("+a[i]+""+a[i+1]+""+a[i+2]+""+a[i+3]+")");
                i++;
                break;
            }
            else if((a[i]==a[i+1])&& (a[i]==a[i+2])){
                System.out.print("("+a[i]+""+a[i+1]+""+a[i+2]+")");
                i++;
                break;
            }
            else if(a[i]==a[i+1]){
                System.out.print("("+a[i]+""+a[i+1]+")");
                i++;
                break;
            }
            else {
                System.out.print(a[i]);
            }
            i++;
        }

    }
    System.out.print(a[19]);

}

}

can anyone show me if there is another way to do it ? thanks :)




Aucun commentaire:

Enregistrer un commentaire