# Arrays (Beginer)

• February 15th, 2012, 03:33 PM
stephen6292
Arrays (Beginer)
i basically have to write code which takes in 5 prices from insurance companies A-E from the user and outputs the average price, and cheapest price with the companies id which would be A,B,C,D,E

here is my code so far, I got it to list the average but cant seem to figure out how to get the cheapest price, or how to make it have the companies id out-putted.

public class InternetCompare
{

public static void main(String[] args)
{

int[] prices = new int[5];

int i = 0;

String s = JOptionPane.showInputDialog(
"enter a price, -1 to stop:");
int n = Integer.parseInt(s);

while ((i <= prices.length - 1) && (n != -1))
{
prices[i] = n;
s = JOptionPane.showInputDialog(
"enter a price, -1 to stop:");
n = Integer.parseInt(s);
i++;
}
int nextFree = i;
// nextFree is index of next free element in array

// compute average age
int total = 0;

for (int j = 0; j < nextFree; j++)
{
total += prices[j];
}

double ave = total / (double) nextFree;

JOptionPane.showMessageDialog(null, "Average price is " + ave);

}
}
• February 15th, 2012, 03:56 PM
Norm
Re: Arrays (Beginer)
Quote:

how to get the cheapest price
Use a loop. Pick the first price as the potential lowest price and compare all the rest of the prices against it looking for one lower. When you find a lower one, save it as the new potential lowest. When done you'll have the lowest
• February 15th, 2012, 04:06 PM
stephen6292
Re: Arrays (Beginer)
how do you mean?, sorry i'm a complete beginner really...
• February 15th, 2012, 04:12 PM
Norm
Re: Arrays (Beginer)
How would you do it manually if there were pieces of paper with numbers on them laid in a row and you could only compare two at a time? Start at the first one and work to the last one. Pick up one and compare it to the next one. If it's lower, lay down the one you are holding and pick up the lower one. Continue until the end.
• February 16th, 2012, 08:13 AM
luck999
Re: Arrays (Beginer)
For problems similar getting cheapest price is not a problem of java, is really a normal problem of algorithm design. It is better for you to read some algorithm design book to understand how to solve this kind of problem before programming.