Results 1 to 2 of 2

Thread: Help sorting arrays

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2010
    Posts
    7

    Help sorting arrays

    Ok so I have this program almost done...just stuck on the sort. I can get the array to sort by name, but the prices do not follow. I want the product prices that are 0-4 to remain with their products 0-4, right order when read into the array. Just cannot seem to get it. I want to sort by name or price as you can see by the code. I am sure its something very simple that I am missing but I cannot put my finger on it.

    Code:
    import javax.swing.*;
    import java.util.*;
    public class CoffeeDriver
    {
    	public static void main(String[] args)
    	{
    		String[] itemSold = new String[5];
    			itemSold[0] = "Coffee";
    			itemSold[1] = "Water";
    			itemSold[2] = "Milk";
    			itemSold[3] = "Bagel";
    			itemSold[4] = "Donut";
    		double[] itemCost = new double[5];
    			itemCost[0] = 1.00;
    			itemCost[1] = 2.00;
    			itemCost[2] = 1.50;
    			itemCost[3] = 1.25;
    			itemCost[4] = 0.75;
    		
    		char choice;
    		choice = JOptionPane.showInputDialog(null, "Welcome to Wings Coffee Shop." + "\nWe have a great list of items on our menu." + "\nWould you like to see our menu sorted by name or price? (n/p):").charAt(0);
    		choice = Character.toLowerCase(choice);
    		switch(choice)
    			{
    			case 'n':
    				methodSortName(itemSold, itemCost);
    				break;
    			case 'p':
    				sortPrice(itemSold, itemCost);
    				break;
    			default:
    				JOptionPane.showMessageDialog(null, "Entry must be n for name or p for price." + "\nPlease try again.");
    				break;
    			}
    	}
    	public static void methodSortName(String itemSold[], double itemCost[])
    	{
    		Arrays.sort(itemSold);
    		int size = itemSold.length;
    		String display = "Item      Price\n";
    		for(int x = 0; x < size; ++x)
    		{
    			display += itemSold[x] + "      " + itemCost[x] + "\n";
    		}
    		JOptionPane.showMessageDialog(null, display);
    	}
    	public static void sortPrice(String[] itemSold, double[] itemCost)
    	{
    		Arrays.sort(itemCost);
    		int size = itemCost.length;
    		String display = "Item      Price\n";
    		for(int x = 0; x < size; ++x)
    		{
    			display += itemSold[x] + "      " + itemCost[x] + "\n";
    		}
    		JOptionPane.showMessageDialog(null, display);
    	}
    }

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Help sorting arrays

    You can use a map to keep your Items bound to their prices.
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width