Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

count occurrences in seven integers using java single dimension arrays

public static int count(int[] arr, int num) {
        int count = 0;
        for(int i = 0; i < arr.length; ++i) {   // go through all elements in array
            if(arr[i] == num) { // if num is found, increase count
                count++;    // increment count
            }
        }
        return count;   // return the count of number of occurrences of num in array
    }

    public static boolean checkIfElementAlreadyExists(int[] arr, int index) {
        for(int i = 0; i < index; ++i) {    // go through all elements in array
            if(arr[i] == arr[index]) {  // if item in index already exists in the array
                return true;    // then return true
            }
        }
        return false;   // if element at index does not previously occur, then return false
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] arr = new int[7];
        System.out.print("Enter seven numbers: ");
        for(int i = 0; i < arr.length; ++i) {
            arr[i] = in.nextInt();  // read 7 numbers into array
        }
        for(int i = 0; i < arr.length; ++i) {   // go through all elements
            if(!checkIfElementAlreadyExists(arr, i)) {  // if this element did not already appear before in the array
                System.out.printf("Number %d occurs %d times.
", arr[i], count(arr, arr[i]));  // then print the number and the number of time it occurs in the array
            }
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: radio button android:inputType 
Java :: int [] to Integer[] 
Java :: java swing dialog box 
Java :: android iinput edit text password icon change 
Java :: how to find length of array in java 
Java :: all installed java 
Java :: java long to hours minutes and seconds 
Java :: como ordenar un arraylist alfabeticamente en java 
Java :: math.absolute java 
Java :: Maven Dependency for flyway 
Java :: heap in java 
Java :: java program for multiplication table 
Java :: map java 
Java :: reverse a string in java 
Java :: set solid color background android programatically in drawable 
Java :: android java shared preferences remove key 
Java :: android menu change text color 
Java :: print string in java 
Java :: array contain java 
Java :: add element in the last in double linked list in java 
Java :: read stream java 
Java :: java instanceof 
Java :: how to use a combo box in java with if else 
Java :: combine two array in java 
Java :: java print 2d array as table 
Java :: com.android.okhttp.internal.http.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection 
Java :: java timeout 
Java :: reverse java 
Java :: java system.out.println not working 
Java :: how to replace an element in array in java 
ADD CONTENT
Topic
Content
Source link
Name
6+3 =