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);
}
}
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.
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.
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With