-2

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

raj_b
  • 1
  • 3
  • What don't you understand? Of course you can't compare a `Food` with an `int`. Do you perhaps intend to compare some `int`-valued property of your `Food`s to the selected `int`? If so, then do *that*. – John Bollinger Jul 23 '22 at 14:19
  • yes, I did understand array objects cannot be compared to an integer, suppose I want to compare the food description if it exists in the array object, what would be the best approach? Thanks for the review. – raj_b Jul 23 '22 at 14:23
  • if the value should be compared to food id then use this if(foodlist[j].getId() == value) also notice the else will make your loop exit also while you still did not searched the whole array –  Jul 23 '22 at 14:25
  • Thanks will try if(foodlist[j].getId() == value) .... but the getId() method is defined as follows: public static int getId() { System.out.println("Input food ID"); return sc.nextInt(); } – raj_b Jul 23 '22 at 14:29
  • The best approach would start with figuring out, in sufficient detail to explain it to us in words, what test you actually want to perform where you have written `foodlist[j] == value`. What do you intend that to do? You mention food description, but that doesn't sound like it would be an `int`, so it also sounds like you may not be conveying the full scope of what you want to do. – John Bollinger Jul 23 '22 at 14:31
  • you welcome @raj_b then you need another method that return the value of the Id field of the Food object or of the filed is public or package private and you have access to it then use the filed name directly so foodlist[j].Id i assume the field name is Id here –  Jul 23 '22 at 14:36
  • The goal of the program is to able search an item by description or index (when comparing with index , it's displaying found even if value is not in array)The search should be able to compare an index or description if it exist in the array of objects. Is there another way to search the array by the food description instead of index? Thks – raj_b Jul 23 '22 at 14:40
  • to search by index just make sure the value is between 0 and array length -1 –  Jul 23 '22 at 15:10
  • @raj_b to search by index just make sure the value is between 0 and array length -1 value >=0 && value < foodlist.length is that true simple use foodlist[value] for description use if(foodlist[j].description.equals( value)) but you need to use String value not int as your code –  Jul 23 '22 at 15:18

2 Answers2

1

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.");
Cheng Thao
  • 1,467
  • 1
  • 3
  • 9
  • Thanks, this method worked out perfectly... :) apologies to the community for not respecting java coding good practice , due to lack of experience (4 month), will try to improve in the future – raj_b Jul 23 '22 at 17:12
0

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.

Persixty
  • 8,165
  • 2
  • 13
  • 35