Home > Software design >  Count the Integer Array Values
Count the Integer Array Values

Time:01-03

how to count the integer values from the code below :

            String arr = [1,0,1,0,1,1];
            String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");

            int[] results = new int[items.length];

            for (int i = 0; i < items.length; i  ) {
                try {
                    results[i] = Integer.parseInt(items[i]);
                } catch (NumberFormatException nfe) {
                    //NOTE: write something here if you need to recover from formatting errors
                };
            }

I want to implement if 0 is more than 1 so will print false and if 1 is more than 0 will print true

CodePudding user response:

public static void main(String[] args) {
    String arg = "[1,0,1,0,0]";
    int amountOfZeros = 0;
    int amountOfOnes = 0;
    for (int i = 1; i <arg.length() ; i= i   2) {
        int numberInArray = Integer.parseInt(String.valueOf(arg.charAt(i)));
        try{
            if(numberInArray == 0){
                amountOfZeros  ;
            }
            if(numberInArray == 1){
                amountOfOnes  ;
            }
        } catch (Exception e){
            System.out.println(e);
        }
    }
    // and now you can print this amounts of numbers and false or true if you need it;
    System.out.println(amountOfZeros <= amountOfOnes);
    //or
    if(amountOfZeros > amountOfOnes){
        System.out.println(false);
    } else {
        System.out.println(true);
    }
    System.out.println(amountOfZeros);
    System.out.println(amountOfOnes);
}

this is how i understand your problem :p

CodePudding user response:

I have implemented it using Java for you and I will explain it below with the code:

    public static void main(String[] args) {
        int[] arr = {1, 0, 1, 0, 1, 1};
        /*
            Here you make a two index array to hold the values
            of 0`s and 1`s as a counter.
         */
        int[] results = new int[2];

        for (int i = 0; i < arr.length; i  ) {
            try {
                //Check if the current index is 0 or 1
                //Then increment the counter.
                if (arr[i] > 0) results[1]  ;
                else results[0]  ;
            } catch (NumberFormatException nfe) {
                //NOTE: write something here if you need to recover from formatting errors
            }
        }
        //Check which one is greater than the other.
        System.out.println(results[1] > results[0] ? "True" : "False");
    }

I hope you found it useful :)

  • Related