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


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Arrays.Sort Help

  1. #1
    Junior Member
    Join Date
    Feb 2011
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Arrays.Sort Help

    I have an array called list that contains string id, and double temp //names and values for weather stations

    I want to sort the list by the value temperature.


    public void Display2()
    {
    Arrays.sort(List);-
    HOW DO I SORT BY TEMP?? GetID is the getter method for string id, and GetTemp is the getter method for GetTemp. Temp and ID were initialized on another .java file --WeahterStationData.java if that helps
    System.out.println("Highest Temperature: " + List[0].GetID() + List[0].GetTemp());
    System.out.println("Lowest Temperature: " + List[CurrSize].GetID() + List[CurrSize].GetTemp());

    }

    Exception in thread "main" java.lang.ClassCastException: WeatherStationData cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Unknown Source)
    at java.util.Arrays.mergeSort(Unknown Source)
    at java.util.Arrays.mergeSort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at WeatherStationList.Display2(WeatherStationList.jav a:58)
    at WeatherStationUI.RunIT(WeatherStationUI.java:36)
    at WeatherStationUI.<init>(WeatherStationUI.java:18)
    at Main.main(Main.java:11)

  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Arrays.Sort Help

    Comparable is an interface.

    If that class doesn't implement Comparable, then it can't be cast to that type.

    You have posted pretty much no code.

    Though I think you're casting something to be a Comparable that isn't.


    The wrapper class Double implements Comparable.

    double value = 0.00
    Double d = value;
    double value2 = 1.00
    Double d2 = value2;

    if (d.compareTo(d2) ==0)
    // values are equal

    else
    {
    if (d.compareTo(d2) < 0)
    // d is less than d2

    else
    // d is greater than d2
    }
    Last edited by javapenguin; February 17th, 2011 at 07:56 PM.

  3. The Following User Says Thank You to javapenguin For This Useful Post:

    Brandon Seale (February 19th, 2011)

  4. #3
    Junior Member
    Join Date
    Feb 2011
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Arrays.Sort Help

    Sorry.

    /*
     * title: Main.java
     * name: Brandon Seale
     * date: 2/16
     * comments: used Happy Inventory as framework for project. 
     */
    public class Main { 
     
    	public static void main(String[] args)
    	{
    		WeatherStationUI NewList = new WeatherStationUI();
    	}
     
    }

    /*
     * Title:			WeatherStationData.java
     * Description:		This represent a single Weather Station
     * 
     */
     
    public class WeatherStationData {
    	private String StationID;  //Each Station must have a unique identifier...
    	private double StationTemp;
     
     
     
    	public WeatherStationData() //Define a default constructor...
    	{
    		StationID = "";		
    		StationTemp = 0.0;
     
    	}
     
    	public WeatherStationData(String ID, double Temp) //...intializer
    	{
    		StationID = ID;
    		StationTemp = Temp;
     
     
     
    	}
     
    	//Define some setter methods...
     
    	public void SetID(String ID)  { StationID = ID; }
    	public void SetTemp(double Temp) { StationTemp = Temp; }
     
     
    	//Define some getter methods...
     
    	public String GetID()  { return StationID; }
    	public double GetTemp()  { return StationTemp; }
     
     
    }

    /*
     * Title:			WeatherStationUI.java
     * Description:		Supplies a frame for using the WeatherStationList class...
     */
     
     
    import java.util.*;
     
     
    public class WeatherStationUI {
     
    	WeatherStationList Collection = new WeatherStationList(); // to store data
    	Scanner Input = new Scanner(System.in); // new scanner
     
     
     
     
    	public WeatherStationUI() { RunIT(); } 
     
    	public void RunIT()
    	{
     
    	   String Command;
     
    	   while(true) {
    		   Menu(); // menu
     
    		   System.out.print("Command: "); //uses next line as command
    		   Command = Input.nextLine();
     
    		if(Command.equals("Quit")) // "Quit" breaks from program
    			   break;
    		   else if(Command.equals("Post Temperatures"))	 
    			   PostTemperatures();	
    [B]	   
    		   else if(Command.equals("High-Low Report")) // to view high low			   
    			   	Collection.Display2();[/B]
    		   else if(Command.equals("Daily Report")) // view all
    			   Collection.Display();
     
    	   }
     
     
    	}
     
     
     
    	public void Menu() //choices
    	{
    		System.out.println("Choices.......................................");
    		System.out.println("\tPost Temperatures...allows the user to post new stations");
    		System.out.println("\tHigh-Low Report...allow the user to view high to low.");
    		System.out.println("\tDaily Report.....displays the entire list.");
    		System.out.println("\tQuit");
    		System.out.println("----------------------------------------------");
    	}
     
    	public void PostTemperatures() //posts temps
    	{
    		String ID, Unit;
    		double Temp;
     
    		while(true){
     
     
    				System.out.print("Station Name: "); //prompts for station name
    				ID = Input.nextLine(); // puts next line as id
     
    				if(ID.equals("Stop")) //breaks
    					break;
     
    				System.out.print("Station Temp: ");
    				Unit = Input.nextLine(); 
    				Temp = Double.parseDouble(Unit); //turns into double
    				Collection.Add(ID, Temp); 
     
     
     
     
     
     
     
    		}
     
     
    	}
     
     
     
     
     
     
     
    }
    /*
     * Title:		WeatherStationList.java
     * Description: this implements and manages a list of inventory items...
     */
    import java.text.DecimalFormat;//in order to display in decimal format
    import java.text.NumberFormat;//same
    import java.util.*;
     
     
    public class WeatherStationList {
     
    	private int MaxSize = 25;  //The value here is the List's absolute size...
    	private int CurrSize = 0;  //The number of item currently list...
     
    	public WeatherStationData[] List = new WeatherStationData[MaxSize];
     
     
     
    	//Define the core methods for the list...
     
    	//First a way to add items to the list...
     
    	public void Add(String ID, double Temp)
    	{
    		if(CurrSize < MaxSize) {  //Make sure there's room...
    			List[CurrSize] = new WeatherStationData(ID, Temp); //Then add it...
    			CurrSize++; //Bump the count up, because there's one more...
    		}
    		else
    			System.out.println("Sorry List Is Full"); //Whoops! no more room...
    	}
     
     
     
     
     
    	public void Display()
    	{
    		int K;
     
    		for(K = 0 ; K < CurrSize ; K++)  {
    			if(List[K] != null) {
    				NumberFormat Rounder = new DecimalFormat("#0.00"); //displays in 0.00 decimal format
     
    				System.out.println("Weather Station:   " + List[K].GetID()); //gets station id
    				System.out.println("Temperature: " + List[K].GetTemp() + "    " + Rounder.format(((5*(List[K].GetTemp()-32))/9)));//shows temp in F and Celcius
     
    			}
    		}
     
     
     
    	}
     
     
    	[B]public void Display2()
    	{
     
                            [QUOTE]What Code Do i enter here to sort the list by the value of the Double Temp?
    			 Arrays.sort(List);
    [/QUOTE]
     
    			System.out.println("Highest Temperature: " + List[0].GetID() + List[0].GetTemp());
    			System.out.println("Lowest Temperature: " + List[CurrSize].GetID() + List[CurrSize].GetTemp());
     
    	}[/B]
     
     
     
     
     
     
     
     
    }

  5. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,237
    Thanks
    176
    Thanked 817 Times in 760 Posts
    Blog Entries
    5

    Default Re: Arrays.Sort Help

    To extend off of javapenguin's post, Arrays.sort (as does Collections.sort) requires the objects to be sorted to implement Comparable. See the following link for details on how to implement this interface Object Ordering.

    EDIT: and crossposted. Not against the rules here, but we ask members to let others know where else the question was asked. See The problems with crossposting
    Last edited by copeg; February 18th, 2011 at 09:37 AM.

  6. #5
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Cool Re: Arrays.Sort Help

    Arrays (Java Platform SE 6)

    Also, that

    while(true)
    thing will almost certainly be an infinite loop. (Unless you have a break somewhere else.)

    Also, you should probably have your Menu() method be changed to this:

     
    public void Menu(String Command)
    {
    System.out.println("Choices.......................................");
    		System.out.println("\tPost Temperatures...allows the user to post new stations");
    		System.out.println("\tHigh-Low Report...allow the user to view high to low.");
    		System.out.println("\tDaily Report.....displays the entire list.");
    		System.out.println("\tQuit");
    		System.out.println("----------------------------------------------");
     
     
    if(Command.equalsIgnoreCase("Quit")) // "Quit" breaks from program
    			   break;
    		   else if(Command.equalsIgnoreCase("Post Temperatures"))	 
    			   PostTemperatures();	
     
    		   else if(Command.equalsIgnoreCase("High-Low Report")) // to view high low			   
    			   	Collection.Display2();
    		   else if(Command.equalsIgnoreCase("Daily Report")) // view all
    			   Collection.Display();
     
    else
    {
    // what happens if they enter an invalid command?
    }
    }
     
    // Also, why are you entering commands instead of say having options associated with each choice and passing it an int as // a parameter and not even bothering with String?  It'd be more convenient for the user of your program if you did it 
    // this way.


    As it is, I have changed it to equalsIgnoreCase(String str) in case they don't start with a capital. Java is very annoyingly picky and will say it's not equal if you do something as trivial as forgetting a space so that it doesn't match up with the thing you have in the equals parameter.

    Very annoying, I know



    the constructor that takes as a parameter the result of a void method is not a good idea.

    If anything, you'd have a no param constructor and do something like this:

    public WeatherStationUI()
    {
    RunIt();
    }

    Third, a Scanner only works that I'm aware of in the main method or at least in a class that has a main method.

  7. The Following User Says Thank You to javapenguin For This Useful Post:

    Brandon Seale (February 19th, 2011)

  8. #6
    Junior Member
    Join Date
    Feb 2011
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Arrays.Sort Help

    Thanks everyone, for help, just finished program. Didn't need to incorporate comparables/compare to for what i'm doing

    -Brandon Seale

Similar Threads

  1. How to Sort an Array using the java.util.Arrays class
    By JavaPF in forum Java SE API Tutorials
    Replies: 2
    Last Post: May 17th, 2014, 01:16 AM
  2. Insertion Sort
    By Kimimaru in forum Algorithms & Recursion
    Replies: 2
    Last Post: December 6th, 2010, 05:26 AM
  3. bubble sort and selection sort on strings
    By Sir Saula in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 3rd, 2010, 09:44 AM
  4. Arrays.sort or iterative search?
    By igniteflow in forum Collections and Generics
    Replies: 1
    Last Post: September 16th, 2009, 02:07 AM
  5. Help with Sort arrays
    By drk in forum Collections and Generics
    Replies: 5
    Last Post: September 6th, 2009, 02:48 AM

Tags for this Thread