Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## 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);

}
}

2. ## Re: Arrays (Beginer)

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

3. ## Re: Arrays (Beginer)

how do you mean?, sorry i'm a complete beginner really...

4. ## 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.

5. ## 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.