1

for my code I have an input method that allows the user to input any number of objects with an item name and price into the array. For the assignment I am also suppose to print out an average value of the prices if the name of an object is "peas". Except every time I run the code even with Peas as a name of an object, it outputs that no average was calculated and that it is equal to zero. Thank you

Also another question, I thought it would be better to just make a seperate method to calculate average. However the array has a max size of 1000, and only the numofEntries variable is in the input method. So I am unable to use that to count up to the number of actual objects in the array. How would I work around this?

public static void input(Item[] arr) {
    Scanner input = new Scanner(System.in);
    int numofEntries = 0;
    double pricesAdded = 0;
    double average = 0;

    for ( int i = 0; i < arr.length; i++) 
    {
        System.out.println("Enter item");
        String item = input.next();

        System.out.println("price");
        double price = input.nextDouble();

        if (price == -1) break;

        arr[i] = new Item(item, price);
        numofEntries++;
    }

    for( int j = 0; j < numofEntries; j++) {
        if(arr[j].getName() == "peas" || arr[j].getName() == "Peas") {
            for( int k = 0; k < numofEntries; k++) { 
                pricesAdded = pricesAdded + arr[k].getPrice();
            }
            break;
        }
    }

    if(average == 0) System.out.println("No average output " + average);
        else System.out.println("The average is " + (average = pricesAdded /  numofEntries));

    for ( int i = 0; i < numofEntries; i++)
        System.out.println(arr[i].toString());
}
Artie
  • 35
  • 6

3 Answers3

1

You attempt to calculate the average value too late. By the time the if condition is calculated, you haven't assigned a value other than 0 to it, so the if condition is satisfied and the else block never runs.

Calculate the average first, before the if statement. Then, in the else block, refer to average.

Also, please refer to How do I compare strings in Java? regarding the line

if(arr[j].getName() == "peas" || arr[j].getName() == "Peas") {
Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Change the if condition to check for pricesAdded, not average, i.e.

if(pricesAdded == 0)

Also, you should change at least the string comparison logic.

Try doing

  if("peas".equalsIgnoreCase(arr[j].getName()) {
      ...
  }
PNS
  • 19,295
  • 32
  • 96
  • 143
0

Your problem is that you are never really calculating the average. You can input numofEntries as an input variable to your other function.

Bjr. Jean
  • 126
  • 1
  • 9