asked 201k views
1 vote
Write a Java program to accept an unlimited number of item names and prices, and output them. In addition output the average price if one of the items is named Peas (not case sensitive) otherwise output : "no average output". The inputs will be terminated by a sentinel price of - 1. (Do not include -1 in the average.)

asked
User PeterKA
by
7.7k points

1 Answer

1 vote

Answer:

// program in java

// package

import java.util.*;

// class definition

class Main

{

// main method of the class

public static void main (String[] args) throws java.lang.Exception{

try{

// scanner object to read input

Scanner scr=new Scanner(System.in);

// string array

String name[] = new String[100];

// price array

double price[] = new double[100];

// variables

double sum = 0,avg;

int i = 0;

boolean flag = false;

// read inputs until user enter a price -1

while(true){

System.out.print("Enter item " + (i + 1) + " name: ");

name[i] = scr.next();

System.out.print("Enter item " + (i + 1) + " price: ");

price[i] = scr.nextDouble();

if(price[i] == -1) break;

if(name[i].equalsIgnoreCase("peas"))

flag = true;

sum += price[i];

i++;

}

// print item and their price

System.out.println("Items and their prices : ");

for(int y = 0; y < i; y++){

System.out.println(name[y] + ": " + price[y]);

}

// find average

avg =sum/i;

if(flag == true){

System.out.println("Average: " + avg);

}

else{

System.out.println("no average output");

}

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Read name and their price from user until user enters a price equals to -1 of an item .print all the names and their price .If any name is equal to "peas" without case sensitive then find the average of all price and print the average.If their is no name equal to "peas" then print "no average output".

Output:

Enter item 1 name: apple

Enter item 1 price: 12

Enter item 2 name: kiwi

Enter item 2 price: 20

Enter item 3 name: peas

Enter item 3 price: 22

Enter item 4 name: banana

Enter item 4 price: -1

Items and their prices :

apple: 12.0

kiwi: 20.0

peas: 22.0

Average: 18.0

answered
User Josanne
by
8.2k points