Results 1 to 4 of 4
  1. #1
    jubbiejub is offline Member
    Join Date
    Mar 2012
    Posts
    16
    Rep Power
    0

    Default Sorting code not working correctly

    EDIT: I'll be back in an hour to answer any questions that you might have that would help you help me. :)

    I'm writing a program that uses polymorphism and inheritance to sort solids from a text file based on surface area and volume. I am pretty much completely done with the project, however the code I am using to sort and display the lists aren't working correctly.

    Here is the code:



    This is my abstract class that defines a solid

    Java Code:
    import java.text.DecimalFormat;
    
    public abstract class Solid {
    
    	private String solidName;
    	DecimalFormat roundHundreth = new DecimalFormat("#.##");
    	
    	//constructor for setting name to a default value
    	//preconditions:none
    	//postconditions:sets solidName to undefined
    	public Solid(){
    		solidName = "undefined";
    	}
    	
    	//method for setting name to method argument
    	//preconditions: must enter a String argument
    	//postconditions: will set solidName to name
    	public void setName(String name){
    		solidName = name;
    	}
    	
    	//getter method for Solid name
    	//preconditions: none
    	//postconditions: will return solidName
    	public String getName(){
    		return solidName;
    	}
    	
    	public char charAt(int index){
    		//charAt method for Solid
    		//preconditions: none
    		//postconditions: returns char at index
    		String name = getName();
    		return name.charAt(index);
    	}
    	
    	
    	//abstract method declarations
    	public abstract double volume();
    	
    	public abstract double surface();
    	
    	public abstract void display();
    	
    	public abstract double getVolume();
    	
    	public abstract double getSurface();
    		
    	
    	
    	
    }


    This is the class that grabs the data from the file and sorts it into two lists, as well as sorting and displaying the information by surface area and volume

    Java Code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    
    public class SolidList{
    
    	SurfaceMeasurer surfaceArea = new SurfaceMeasurer();
    	VolumeMeasurer volume = new VolumeMeasurer();
    	Scanner fileReader;
    	Solid[] list = new Solid[201];
    	Solid[] list2 = new Solid[201];
    	int count = 0;
    	
    	
    	public void getData(){
    		//method to put the data from the files into Solid arrays
    		//preconditions: none
    		//postconditions: will assign each value from the file on ascending array indexes
    		
    		try {
    			fileReader = new Scanner(new File("data.txt"));
    			} 
    		catch (FileNotFoundException e) {
    			e.getMessage();
    			}
    		
    		do{
    			
    				String inputLine = fileReader.nextLine();
    				String[] temp = inputLine.split("\t");
    				
    				
    				if(temp[0].equals("S")){
    					
    					double radius = Double.parseDouble(temp[1]);
    					list[count] = new Sphere(radius);
    					list2[count] = new Sphere(radius);
    				}	
    				else if(temp[0].equals("C")){
    					
    					double side = Double.parseDouble(temp[1]);
    					list[count] = new Cube(side);
    					list2[count] = new Cube(side);
    				}
    				else if(temp[0].equals("R")){
    					
    					double length = Double.parseDouble(temp[1]);
    					double width = Double.parseDouble(temp[2]);
    					double height = Double.parseDouble(temp[3]);
    					list[count] = new Rectangular(length, width, height);
    					list2[count] = new Rectangular(length, width, height);	
    				}
    				++count;
    			}
    		while(fileReader.hasNextLine());
    		}
    		
    					
    			
    		
    	
    
    	
    	
    	public void displayData(){
    		//method to print out the data retrieved from the text file
    		//preconditions: none
    		//postconditions: prints out data
    		
    		getData(); 
    		
    		System.out.println("List sorted by ascending surface area: \n");
    		
    		for(int i = list.length - 1; i >= 0; --i){
    			
    			int highestIndex = i;				
    			
    			for(int j = i; j >= 0; --j){
    			
    				if(surfaceArea.getMeasure(list[j]) > surfaceArea.getMeasure(list[highestIndex])){	
    					highestIndex = j;		
    			}
    				
    				Solid temp = list[i];
    				list[i] = list[highestIndex];
    				list[highestIndex] = temp;
    		
    			}
    		
    			for(int x = 0; x < list.length; ++x){
    				
    				list[x].display();	
    			}
    			
    			System.out.println("\n");
    			
    			System.out.println("List sorted by ascending volume: \n");
    			
    			for(int x = list2.length - 1; x >= 0; --x){
    				
    				int highest = x;				
    				
    				for(int j = x; j >= 0; --j){
    				
    					if(volume.getMeasure(list2[j]) > volume.getMeasure(list2[highest])){	
    						highest = j;		
    				}
    					
    					Solid temp = list2[x];
    					list2[x] = list2[highest];
    					list2[highest] = temp;
    			
    				}
    			
    				for(int k = 0; k < list2.length; ++k){
    					
    					list2[k].display();
    					
    				}
    			}
    		}
    }
    		
    	
    	//This is just a test at the moment, actual main will be in another class
    	public static void main(String[] args){
    		
    		SolidList jaron = new SolidList();
    		jaron.displayData();	
    		}
    		
    	}


    I have two measurer classes, one for surface area and one for volume. This is one of them

    Java Code:
    public class SurfaceMeasurer implements Measurer {
    
    	
    	public double getMeasure(Object x) {
    		Solid s = null;
    		
    		if (x instanceof Cube){
    			s = (Cube) x;
    			double surface = s.surface();
    			return surface;
    		}
    		else if(x instanceof Sphere){
    			s = (Sphere) x;
    			double surface = s.surface();
    			return surface;
    		}
    		else if (x instanceof Rectangular){
    			s = (Rectangular) x;
    			double surface = s.surface();
    			return surface;
    		}
    		else return 0;
    		
    	}
    
    }
    Here is one of my child classes of solid, they all look the same but for different shapes (Rectangular, Sphere, Cube)

    Java Code:
    public class Rectangular extends Solid {
    	
    	private double length;
    	private double width;
    	private double height;
    	
    	public Rectangular(){
    		setName("undefined");
    	}
    	
    	public Rectangular(double len, double wid, double hei){
    		
    		setName("Rectangular");
    		length = len;
    		width = wid;
    		height = hei;
    	}
    	
    
    	public double volume() {
    		//method to return volume of a rectangular prism
    		//preconditions: must use defined constructor while instantiating Rectangular 
    		//postconditions: computes and returns volume
    		
    		double vol = length*width*height;
    		return vol;
    	}
    
    	
    	public double surface() {
    		//method to return surface area of a rectangular prism
    		//preconditions: must use defined constructor while instantiating Rectangular 
    		//postconditions: computes and returns surface area
    		
    		double surfaceArea = 2*length*height + 2*height*width + 2*length*width;
    		return surfaceArea;
    	}
    
    	
    	public void display() {
    		//method to display info on a rectangular prism
    		//postconditions: none
    		//postconditions: displays information related to a rectangular prism
    		
    		System.out.printf("Rectangular Prism -- Length: %s   ||   Width: %s   ||   Height: %s   ||   Volume: %s   ||   Surface Area: %s\n", roundHundreth.format(length), roundHundreth.format(width), roundHundreth.format(height), roundHundreth.format(volume()), roundHundreth.format(surface()));
    		
    	}
    
    	@Override
    	public double getVolume() {
    		// TODO Auto-generated method stub
    		return volume();
    	}
    
    	@Override
    	public double getSurface() {
    		// TODO Auto-generated method stub
    		return surface();
    	}
    }
    The text in the text file is

    S 0.5
    C 0.75
    R 1.5 5.2 3.75
    R 40.0 1.0 1.0
    C 7.5
    C 75.0
    S 37.5
    S 1.0
    S 1.25
    R 74.0 76.0 11.5
    C 3.14
    C 1.77


    Whenever I run the code, I get the output

    List sorted by ascending surface area:

    Sphere -- Radius: 0.5 || Volume: 0.39 || Surface Area: 3.14
    Cube -- Side: 0.75 || Volume: 0.42 || Surface Area: 3.38
    Rectangular Prism -- Length: 1.5 || Width: 5.2 || Height: 3.75 || Volume: 29.25 || Surface Area: 65.85
    Rectangular Prism -- Length: 40 || Width: 1 || Height: 1 || Volume: 40 || Surface Area: 162
    Cube -- Side: 7.5 || Volume: 421.88 || Surface Area: 337.5
    Cube -- Side: 75 || Volume: 421875 || Surface Area: 33750
    Rectangular Prism -- Length: 74 || Width: 76 || Height: 11.5 || Volume: 64676 || Surface Area: 14698
    Sphere -- Radius: 1 || Volume: 3.14 || Surface Area: 12.57
    Sphere -- Radius: 1.25 || Volume: 6.14 || Surface Area: 19.63
    Cube -- Side: 3.14 || Volume: 30.96 || Surface Area: 59.16
    Cube -- Side: 1.77 || Volume: 5.55 || Surface Area: 18.8
    Exception in thread "main" java.lang.NullPointerException
    at SolidList.displayData(SolidList.java:93)
    at SolidList.main(SolidList.java:130)

    First of all, why is it not sorting correctly, and second, why in the world is
    for(int x = 0; x < list.length; ++x){

    list[x].display();
    }
    throwing a null pointer exception?

    Help is direly needed.
    Last edited by jubbiejub; 04-30-2012 at 11:47 PM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,307
    Rep Power
    25

    Default Re: Sorting code not working correctly

    throwing a null pointer exception?
    Please post the full text of the error message. If you can, find the line where it occurred and the variable that was null. The backtrace in the code to see why that variable does not have a valid non-null value.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jubbiejub is offline Member
    Join Date
    Mar 2012
    Posts
    16
    Rep Power
    0

    Default Re: Sorting code not working correctly

    Quote Originally Posted by Norm View Post
    Please post the full text of the error message. If you can, find the line where it occurred and the variable that was null. The backtrace in the code to see why that variable does not have a valid non-null value.
    I posted the full error text. It occurs at line 93, which is my "list[x].display();" line in my for loop after I sort everything.(NEVERMIND)

    While I was typing out that sentence I realized what the issue was. Now all I have to do is simply figure out why my sorting code:

    Java Code:
    System.out.println("List sorted by ascending surface area: \n");
             
            for(int i = list.length - 1; i >= 0; --i){
                 
                int highestIndex = i;              
                 
                for(int j = i; j >= 0; --j){
                 
                    if(surfaceArea.getMeasure(list[j]) > surfaceArea.getMeasure(list[highestIndex])){   
                        highestIndex = j;      
                }
                     
                    Solid temp = list[i];
                    list[i] = list[highestIndex];
                    list[highestIndex] = temp;
    }
             
                for(int x = 0; x < list.length; ++x){
                     
                    list[x].display(); 
                }
    isn't sorting correctly. It should sort the list array from smallest surface area to largest surface area. Any help in that respect?

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,307
    Rep Power
    25

    Default Re: Sorting code not working correctly

    Try debugging the code by adding lots of println statements that show the values of variables as they are used and changed.
    The print out will show what the computer sees and help you understand what the code is doing.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Why isn't this snipet of code working correctly
    By josho493 in forum New To Java
    Replies: 4
    Last Post: 04-19-2012, 09:59 AM
  2. Help with If/Else not working correctly?
    By kalaiss in forum New To Java
    Replies: 8
    Last Post: 04-16-2012, 06:32 AM
  3. method not working correctly
    By r1b in forum New To Java
    Replies: 4
    Last Post: 01-04-2012, 08:09 PM
  4. Applet not working correctly?
    By Beavotropper2 in forum Java Applets
    Replies: 2
    Last Post: 04-18-2011, 06:32 AM
  5. [SOLVED] \t not working correctly?
    By Gakusei in forum New To Java
    Replies: 5
    Last Post: 05-06-2008, 04:45 PM

Posting Permissions

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