Best way to get data from a text file and then put it in an array of Solids?
I am writing a program that uses inheritance and polymorphism to sort solids.
Here is my Solids class, which is the parent of Rectangular, Sphere, and Cube.
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;
}
//abstract method declarations
public abstract double volume();
public abstract double surface();
public abstract void display();
}
And here is what one of child classes look like.
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()));
}
}
I am wondering what the most efficient way to sort this text into an object of their respective class. (S = Sphere, etc) I already have a way to do it, but I feel like it could be far more efficient. How would you go about it?
S 0.5
R 1.5 5.2 3.75
R 40.0 1.0 1.0
C 0.75
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
Re: Best way to get data from a text file and then put it in an array of Solids?
What I see of your code seems ok so far - though I would change the name display() to toString(). What part of the posted code is your concern?