Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - searching all elements indexes in array equal to given number

Tags:

java

arrays

I have method searchSales() which is supposed to find all sales figures which are equal to the given sales figure.The application asks the user to enter the given sales figure using the keyboard and searches for it. If sales figure entered from the keyboard is found then the application displays sales figure/figures otherwise it displays an appropriate message. Well, i have a code which displays only first index of equal sales figure, for example: array has elements 1,2,3,3,4,5 and I want to find all indexes of [array] = 3. How can I do this?

public static void searchSales(int search[]){

        Scanner input = new Scanner(System.in);

        System.out.print("Enter sales figure you want to find: ");
        int target = input.nextInt();
        int index = -1;
        for (int i=0; i<search.length; i++){
            if (search[i] == target){
                index=i;
                break;
            }
        }
        if (index == -1){
            System.out.println("Sales figure not found");
        }
        else {
            System.out.printf("Sales figure found at branch %d",index+1);
        }
    }
like image 632
Nataly Avatar asked Sep 11 '12 01:09

Nataly


People also ask

How do you check if all elements in an array are equal to a value?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.

How do you find the index of a number in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.


1 Answers

 public static void searchSales(int search[]){

    Scanner input = new Scanner(System.in);
    System.out.print("Enter sales figure you want to find: ");
    int target = input.nextInt();
    int index = -1;
    for (int i=0; i<search.length; i++){
        if (search[i] == target){
            index=i;
            System.out.printf("Sales figure found at branch %d\n",index+1);

        }
    }
    if (index == -1){
        System.out.println("Sales figure not found");
    }

}
like image 140
rookiepupil Avatar answered Sep 23 '22 10:09

rookiepupil