Home > Net >  Linear and Binary search in an array of objects in java
Linear and Binary search in an array of objects in java

Time:07-24

I'm creating an array of objects where the search should be by Linear method and Binary method.

The issue is how to traverse the array with the appropriate data type and compare.

public class FoodMain {

static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
    
    Food[] foodlist = new Food[3];
    
    //Initialising food objects array
    for (int i = 0; i < foodlist.length; i  ) {
        foodlist[i] = new Food(Food.getId(), Food.getDescription(), Food.getIngredients(), Food.getSellingPrice()); 
    }
    
    FoodMain foodObj = new FoodMain();
    foodObj.show(foodlist);
    
    System.out.print("Enter the search value: ");
    int value = sc.nextInt(); 
    
    for(int j=0; j < foodlist.length; j  ) {
        // Error on line Incompatible operand types Food and int
        if(foodlist[j] == value) {
            System.out.println("The value "   value   " is at index "   j);
            break;
        }
        else {
            System.out.println("Value not in array!!!");
            break;
            }
        }

}

screenshot of object array to be searched Array Objects

Here is the code for Food class

package foodObjectArray;

import java.util.Scanner;

public class Food {

static Scanner sc = new Scanner(System.in);

public  int id;
public  String description;
public  String ingredients;
public  double sellingPrice;

// Food Class constructor
public Food(int id, String description, String ingredients, double sellingPrice) {
super();
this.id = id;
this.description = description;
this.ingredients = ingredients;
this.sellingPrice = sellingPrice;
}


public static int getId() {
    System.out.println("Input food ID");
    return sc.nextInt();
}



public static String getDescription() {
    System.out.println("Input food description");
    return sc.next();
}



public static String getIngredients() {
    System.out.println("Enter the Ingredients");
    return sc.next();
}



public static double getSellingPrice() {
    System.out.println("Input food Price");
    return sc.nextDouble();
}

hope that this might help in my explanation

CodePudding user response:

There's at least a couple of errors here.

Firstly don't you want if(foodlist[j].id == value) {? The will relieve the incompatible operands. You need to specify the field you're trying to match.

The style police will hate your code and demand you define getters and setters. But you don't have let them in without a warrant. ;)

Also when you've fixed that your code will output 'Value not in array!!!' for every item not matching the search value.

You need to move the 'not found' check outside the the for-loop. But let's take this one step at a time.

CodePudding user response:

Let's ignore all of the other problems, and just focus on your linear search. Let's assume you are searching by id.

    for(int j=0; j < foodlist.length; j  ) {
        if(foodlist[j].id == value) {
            System.out.println("The value "   value   " is at index "   j);
            break;
        }
        else {
            System.out.println("Value not in array!!!");
            break;
            }
        }

}

The else branch will break the loop if the first item is not a match. It's not going to search the entire array. It's really is just looking at the first item in the array.

You need to remove the else branch and use a flag (boolean) or some other variable to indicate found.

int foundIndex = -1;   //-1 means not found.

for(int j=0; j < foodlist.length; j  ) {
  if(foodlist[j].id == value) {
    foundIdex = j;
    break;
   }
}

if (indexFound > -1)
  System.out.println("Found at "   indexFound);
else 
  System.out.println("Not found.");
  • Related