mardi 30 novembre 2021

Count repeated elements in Java without using loops or imports

for training purposes i tried to code a programm wich counts how often a given number appears in an given int array. Then checks if the number is even or odd. Without using any imports or loops. I tried to solve it recursive. For Example:

(3, new int[]{3,3,4,5,3,3,2,1})

There are 4 threes, so the Programm should check if 4 is even or odd.

public static int evenNumberOf(int num, int[] numarr) {

After days of coding and not working code i decieded to ask here: any Solutions?

int i = 0 ;
        int counter = 0;
        if(a == null || a.length == 0) {
            return false;
        } else {
            if(a[i] == a.length -1 ) {
                if(counter % 2 == 0) {
                    System.out.println("true");
                    return true;
                    
                } else System.out.println("false");
                    return false;
                
            } else {
            if(a[i] == n) {
                counter++;
                i++;
                return evenNumberOf(n,a) ;
            } else {
                i++;
                return evenNumberOf(n,a) ;

Aucun commentaire:

Enregistrer un commentaire