Store objects in ArrayList and output Object description - java

I am writing a program with separate files in the same package. What I want to do is to use in my Main.java file :
1-Use the values entered by the user create three Triangle objects and stores them in an ArrayList.
2-Display the string representation of each Triangle object in the ArrayList, by calling its toString( ) method and its getArea() method. See the output example below.
I want all the ouput to display after all the inputs. What I mean is that I want the description of each triangle object to be displayed at the end
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("*******************************************************************");
System.out.println("* This program gets input for three triangles from the user. *\n" + "* It then creates three Triangle objects and displays the *\n" + "* description of each.. *");
System.out.println("*******************************************************************");
System.out.println(); // for adding blank line
Scanner input = new Scanner(System. in );
Triangle triangle; //Define the triangle object
ArrayList < GeometricObject > list = new java.util.ArrayList < >();;
for (int i = 1; i < 2; i++) {
System.out.print("Enter the color of a triangle" + i + "(e.g. \"red\"): ");
String color = input.next();
System.out.print("Is the triangle filled (y or n): ");
boolean filled;
String filledString = input.next();
filled = filledString.equals("y"); // condition returns true if "y" is entered
// User input for triangle's 3 sides
System.out.println("Enter the lengths of the three sides of the triangle: ");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
// we need to create the triangle object with the input
triangle = new Triangle(side1, side2, side3);
triangle.setColor(color); // calls setColor from GeometricObject
triangle.setFull(filled); // calls setFilled as well
// Display the triangle, very similar to TestCircleRectangle.java example
System.out.println(); // for adding blank line
System.out.println("Triangle: side1 = " + side1 + "," + " side2 = " + side2 + "," + " side3 = " + side3);
System.out.println(triangle.toString());
System.out.printf("Area = %.2f\n", triangle.getArea());
System.out.println(); // for adding blank line
}
System.out.println("Goodbye...");
}
}
Triangle.java
public class Triangle extends GeometricObject {
// Contains 3 double data fields value to 0
private double side1;
private double side2;
private double side3;
/** Default constructor that creates a triangle
* with default side of 1.0 each
* */
Triangle() {
side1 = 1.0;
side2 = 1.0;
side3 = 1.0;
}
/** parameterized constructor that creates
* a triangle with sides values
* */
Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
/** Getter for side1 */
public double getSide1() {
return side1;
}
/** Setter for side1 */
public void setSide1(double newSide1) {
side1 = newSide1;
}
/** Getter for side2 */
public double getSide2() {
return side2;
}
/** Setter for side2 */
public void setSide2(double newSide2) {
side2 = newSide2;
}
/** Getter for side3 */
public double getSide3() {
return side3;
}
/** Setter for side3 */
public void setSide3(double newSide3) {
side3 = newSide3;
}
/**
* The getArea Method
* Purpose: Computes the area of a triangle from 3 sides
* #return the area of a triangle
*/
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
}
GeometricObject.java
public class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/** Construct a default geometric object */
public GeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with the specified color
* and filled value */
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
this.dateCreated = new java.util.Date();
}
/** Return color */
public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
this.color = color;
}
/** Return filled. Since filled is boolean,
its getter method is named isFilled
*/
public boolean Full() {
return filled;
}
/** Set a new filled */
public void setFull(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}
/**
* Abstract method getArea
*/
/** Return a string representation of this object */
public String toString() {
return "created on " + getDateCreated() + "\ncolor: " + color + " and filled: " + filled;
}
}

(This should probably be more of a comment than an answer, but I am not sufficiently well known in these parts to comment. I am working on that!).
As NotZack said, you haven't actually told us what the problem is. For example, showing us the program's current output compared to what you are aiming for (literally, write down what you want the program to print) would help us know where to start looking.
However, I did notice a few things from quickly looking through your code:
you declare an ArrayList in the main file, but I don't see it being used anywhere. What was the intention of this item?
take a deep, deep look at the following line from main:
for (int i = 1; i < 2; i++)
Get yourself a pen and piece of paper, and write down each value of i in turn which this loop will deal with, bearing in mind the starting value and strictly less than condition. Is this what you want it to do?
Hopefully that gives you something to start working with :)

First you need to add the triangle object to list. And move all the code related to printing triangle move outside the for loop.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<GeometricObject> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
System.out.print("Enter the color of a triangle" + i + "(e.g. \"red\"): ");
String color = scan.next();
System.out.print("Is the triangle filled (y or n): ");
boolean filled = scan.next().equalsIgnoreCase("y");
System.out.println("Enter the lengths of the three sides of the triangle: ");
double side1 = scan.nextDouble();
double side2 = scan.nextDouble();
double side3 = scan.nextDouble();
Triangle triangle = new Triangle(side1, side2, side3);
list.add(triangle);
}
list.forEach(System.out::println);
//Equivalent for above line
/*for(GeometricObject shape: list){
System.out.println(shape);
}*/
}
And also add the toString() method in Triangle class
You don't need to call the toString() method explicitly when you try to print the object it will automatically call the toString() method.
#Override
public String toString() {
return "Triangle: " +
"side1=" + side1 +
", side2=" + side2 +
", side3=" + side3 +
", Area=" + getArea() +
"\n" + super.toString();
}

Related

Initialising and interacting with class in separate switch-case statements

I am currently trying to learn java.
To my current knowledge, I understand it is an OO-based language. I am trying to create a simple class "Circle" with basic parameters (radius, area).
Main function:
import java.util.*;
public class CircleApp
{
public static void main(String[] args)
{
int choice = 1;
while (choice!=4)
{
System.out.println("==== Circle Computation =====");
System.out.println("|1. Create a new circle |");
System.out.println("|2. Print Area |");
System.out.println("|3. Print circumference |");
System.out.println("|4. Quit |");
System.out.println("=============================");
Scanner sc1 = new Scanner(System.in);
choice = sc1.nextInt();
switch (choice)
{
case 1:
{
int rad;
System.out.println("Enter the radius to compute the area and circumference: \n");
Scanner sc2 = new Scanner(System.in);
rad = sc2.nextInt();
Circle circ1 = new Circle(rad);
circ1.setRadius(rad);
circ1.area();
circ1.printArea(circ1);
break;
}
case 2:
{
circ1.area();
Circle.printArea(circ1);
break;
}
case 4:
{
break;
}
default:
{
System.out.println("Choice unknown");
}
}
}
}
}
Circle class:
import java.util.*;
import java.lang.Math;
public class Circle
{
private double radius; // radius of circle
private double area;
private double circumference;
private static int numCircle;
private static final double PI = 3.14159;
// constructor
public Circle(double rad)
{
this.radius = rad;
numCircle++;
}
public Circle()
{
radius = 1.0;
}
// mutator method – set radius
public void setRadius(double rad)
{
this.radius = rad;
}
// accessor method – get radius
public double getRadius()
{
return this.radius;
}
// calculate area
public double area()
{
return area = PI * Math.pow(radius, 2);
}
// calculate circumference
public double circumference()
{
return circumference = 2 * PI * radius;
}
// print area
public static void printArea(Circle c)
{
System.out.println("Radius: " + c.radius);
System.out.println("Area: " + c.area);
}
// print circumference
public void printCircumference()
{
System.out.println("Radius: " + radius);
System.out.println("Circumference: " + circumference);
}
}
Currently, I am trying to create an instance of class Circle within case 1 of my switch case. However, I am unable to get case 2 (calculate and print area) to run properly. While there is the simple workaround of initialising the object outside the switch case, I was wondering if there is a workaround if I were to initialise the object this way instead.
I understand from other sources that the compiler may not respond well to such a scenario as the initialisation of the object is isolated to case 1, which is not guaranteed to be selected first either. Is there a work-around to the issue I am facing or must I initialize the object outside the switch case? Thank you!

Passing values from one nonstatic method to another from main?

I'm having trouble using non static methods. I'm trying to get the value of my "side" variable from a method and plug them into another method which will calculate area. Is there a way to do this without changing the methods to static? None of the previously answered questions on here are helping and neither is my textbook.
import java.util.*;
public class CubeVolume
{
int side1;
int side2;
int side3;
public void getSides()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the length of side1");
side1 = input.nextInt();
System.out.println("Enter the length of side2");
side2 = input.nextInt();
System.out.println("Enter the length of side3");
side3 = input.nextInt();
}
public int getVolume(int side1, int side2, int side3)
{
int volume = side1 * side2 * side3;
return volume;
}
public static void main(String[] args)
{
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
}
I think the problem is with my method call cube.getVolume(side1, side2, side3); because the compiler tells me that non-static variable cannot be referenced from a static context.
If you want to use methods within main() then those methods must be static since main() is static. So you methods should be declared as:
public static void getSides() { .... }
public static int getVolume(int side1, int side2, int side3) { .... }
You can however avoid all this if you tell an instance of your class to start from a non-static method from within your main() method:
public static void main(String[] args) {
new CubeVolume().startApp(args);
}
private void startApp(String[] args) {
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
Now your other methods in the class do not need to be static since you're not calling them from static main().
There is no need to pass in any parameters to getVolume(), just use the class variables:
import java.util.Scanner;
class CubeVolume {
private int side1;
private int side2;
private int side3;
private void getSides() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of side1: ");
side1 = input.nextInt();
System.out.print("Enter the length of side2: ");
side2 = input.nextInt();
System.out.print("Enter the length of side3: ");
side3 = input.nextInt();
input.close();
}
private int getVolume() {
return side1 * side2 * side3;
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.valueOf(cube.getVolume());
System.out.println("The cubes volume is: " + cubeVolumeString);
}
}
Example Usage:
Cube Volume Calculator
======================
Enter the length of side1: 3
Enter the length of side2: 4
Enter the length of side3: 5
The cube's volume is: 60
Alternative approach which stores the side lengths in a double array, sides, and deals with possible invalid input in getSides():
import java.util.Scanner;
class CubeVolume {
private double[] sides;
CubeVolume() {
sides = new double[3];
}
private void getSides() {
Scanner scanner = new Scanner(System.in);
int currentSide = 0;
while (currentSide < sides.length) {
System.out.printf("Enter the length of side %d: ", currentSide + 1);
double nextSide = 0.0;
input:
while (scanner.hasNext()) {
if (scanner.hasNextDouble()){
nextSide = scanner.nextDouble();
if (nextSide > 0) {
sides[currentSide] = nextSide;
break input;
} else {
System.out.println("ERROR: Input number was too small.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
}
} else {
System.out.println("ERROR: Invalid input, please input a number.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
scanner.next();
}
}
currentSide++;
}
scanner.close();
}
private double getVolume() {
return sides[0] * sides[1] * sides[2];
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.format("%.2f", cube.getVolume());
System.out.println("The cube's volume is: " + cubeVolumeString);
}
}
Example Usage 2:
Cube Volume Calculator
======================
Enter the length of side 1: a
ERROR: Invalid input, please input a number.
Enter the length of side 1: -1.1
ERROR: Input number was too small.
Enter the length of side 1: 3.4
Enter the length of side 2: 4.7
Enter the length of side 3: 5.8
The cube's volume is: 92.68
You need not to pass sides parameters to get valume function because your sides variable will be available to get valume function.

Writing Classes: Creating a RightTriangle class that works with the given tester

I am doing an assignment and kinda lost now. The assignment requires me to make a RightTriangle class that works with the given driver. Here are the details:
Your RightTriangle class will need two constructors:
A parameterized constructor that takes the two legs of the triangle and calculates the hypotenuse. Throw an exception if either leg is less than or equal to zero.
A default constructor that sets the two legs to 1 and calculates the hypotenuse. This constructor should call your parameterized constructor using the "this" command.
Your RightTriangle class will need the following public methods:
A getArea() method that returns a double
A getPerimeter() method that returns a double
A toString method() that returns a String in the following format: "A right triangle with edges 1.0, 1.0, and hypotenuse 1.4142135623730951."
RightTriangleDriver.java
import java.util.*;
public class RightTriangleDriver
{
public static void main(String[] args)
{
/*
Menu:
1 - test default constructor and toString
2 - test parameterized constructor and toString
3 - test getArea
4 - test getPerimeter
*/
Scanner kb = new Scanner(System.in);
int option = kb.nextInt();
switch(option)
{
case 1: //1 - test default constructor and toString
try
{
System.out.println("Testing default constructor, then toString()");
RightTriangle r = new RightTriangle();
System.out.println("Got: " + r);
}
catch(Throwable ex)
{
System.out.println("\tgot: " + ex);
}
break;
case 2: //2 - test parameterized constructor and toString
try
{
System.out.println("Testing parameterized constructor, then toString()");
double side1 = kb.nextDouble();
double side2 = kb.nextDouble();
RightTriangle r = new RightTriangle(side1, side2);
System.out.println("Got: " + r);
}
catch(Throwable ex)
{
System.out.println("Got: " + ex);
}
break;
case 3: //3 - test getArea
try
{
System.out.println("Testing getArea()");
double side1 = kb.nextDouble();
double side2 = kb.nextDouble();
RightTriangle r = new RightTriangle(side1, side2);
System.out.println("Got: " + r.getArea());
}
catch(Throwable ex)
{
System.out.println("Got: " + ex);
}
break;
case 4: //4 - test getPerimeter
try
{
System.out.println("Testing getPerimeter()");
double side1 = kb.nextDouble();
double side2 = kb.nextDouble();
RightTriangle r = new RightTriangle(side1, side2);
System.out.println("Got: " + r.getPerimeter());
}
catch(Throwable ex)
{
System.out.println("Got: " + ex);
}
break;
default:
System.out.println("I don't understand your request");
}
}
}
This is what I've got so far
public class RightTriangle
{
private double side1;
private double side2;
//constructors
public RightTriangle()
{
this(1.0, 1.0);
}
public RightTriangle(double s1, double s2)
{
if(s1 > 0 && s2 > 0)
side1 = s1;
side2 = s2;
else
throw new IllegalArgumentException("All triangle edges must have positive length");
}
//Methods
public String toString()
{
return "A right triangle with edges " + side1 + ", " + side2 + " , and hypotenuse " + Math.sqrt((side1 * side1) + (side2 * side2)) + ".";
}
//get Area
public double getArea()
{
return side1 * side2 / 2;
}
//get Perimeter
public double getPerimeter()
{
return side1 + side2 + Math.sqrt((side1 * side1) + (side2 * side2));
}
//get hypotenuse
public double getHypotenuse()
{
return Math.sqrt((side1 * side1) + (side2 * side2));
}
I'm stuck because I don't know how to make them work with all tests. Any advice would be appreciated!.
I may have missed something but is seems like you just need to override toString for RightTriangle according to the specifications in the assignment.
I can elaborate if you want to. I would have posted this as a comment if i had the reputation to do so.
EDIT:
RightTriangle r = new RightTriangle();
System.out.println("Got: " + r);
This code is from RightTriangleDriver. When p, a RightTriangle object is given to System.out.println, its toString() value is printed.
It is therefore identical to the following:
RightTriangle r = new RightTriangle();
System.out.println("Got: " + r.toString());
From the specifications in the assignment:
Your RightTriangle class will need the following public methods:
...
A toString method() that returns a String in the following format: "A right triangle with edges 1.0, 1.0, and hypotenuse 1.4142135623730951."
EDIT 2: A more detailed description of toString
toString exists for every object in java. By default, your own classes' toString methods will return something like "RightTriangle#l13e8ed".
In the specification for this assignment, you were tasked to make your toString() return a specific description of the object rather than the default. We achieve this by overriding the toString method.
When you want to Override a method, you create a new one with the same declaration (Return type, name, and parameter types) as the one in the superclass. There are more advanced rules but in general you just create a method with the same declaration. In this case, creating a public String toString() in RightTriangle will override the toString() that exists by default:
public String toString(){
return "A right triangle with edges " + firstSide + ", " + secondSide +", and hypotenuse " + hypotenuse + ".";
}

Why will this not return the area?

class TestShapes {
public static void main(String[] args){
Scanner input = new Scanner(System.in); // creates the scanner class
System.out.print("Enter the numer of shapes: "); // asks user for input
int N = input.nextInt(); // stores the user input as N
Shape [] myShape = new Shape[N]; // will create as many shapes (N) in an array
for(int i=0;i<N;i++)
{
System.out.println("Enter the choice (Square, Rectangle, Circle):");
int select = input.nextInt();
if(select == 1)
{
//user wanted a Square
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the side length of the square: ");
double s = input.nextDouble();
myShape[i] = new Square(c,s);
}
else if(select == 2)
{
//user wanted a Rectangle
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the length of the rectangle: ");
double l = input.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double w = input.nextDouble();
myShape[i] = new Rectangle(c,l,w);
}
else if(select == 3)
{
//user wanted a Circle
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the radius of the circle: ");
double r = input.nextDouble();
myShape[i] = new Circle(c,r);
}
}
for(int i=0;i<N;i++) //this will print the details
{
System.out.println("\nShape "+ (i+1)+ ":");
myShape[i].print();
}
}
}
class Shape {
String color;
double area;
public Shape(){ // default constructor
color = "red";
}
public Shape(String c){ // constructor
color =c;
}
public String getColor(){ //accessors
return color;
}
public void setColor(String c){//mutators
color=c;
}
//print method
public void print()
{
System.out.println("Color: "+ getColor());
}
public double area(){
return area;
}
}
class Square extends Shape{ // inherits from the shape class
double sideLength;
public Square(){//default constructor
super();
sideLength = 1;
}
public Square(String c, double s){ //constructor
super(c);
sideLength = s;
}
public double getSideLength(){//accessor
return sideLength;
}
public void setSideLength(double s){//mutator
sideLength = s;
}
public double area(){
return sideLength * sideLength; //calculates the area of the square
}
public void print()
{
super.print();
System.out.println("Side length: " + getSideLength()
+ "\nArea: " + area);
}
}
class Rectangle extends Shape{// inherits from the shape class
double length;
double width;
public Rectangle(){//default constructor
super();
length = 1;
width = 1;
}
public Rectangle(String c, double l, double w){ //constructor
super(c);
length = l;
width = w;
}
public double getLength(){//accessor
return length;
}
public double getWidth(){//accessor
return width;
}
public void setLength(double l){//mutator
length = l;
}
public void setSideLength(double w){//mutator
width = w;
}
public double area(){
return length * width; //calculates thea area of the rectangle
}
public void print()
{ // prints out the information
super.print();
System.out.println("Length: " + getLength() + "\nWidth:"+ getWidth() + "\nArea: "+ area);
}
}
class Circle extends Shape{// inherits from the shape class
double radius;
public Circle(String c, double r){//default constructor
super(c);
radius = 1;
}
public Circle(double r){ //constructor
super();
radius = r;
}
public double getRadius(){//accessor
return radius;
}
public void setRadius(double r){//mutator
radius = r;
}
public void print()
{ // prints out the information
super.print();
System.out.println("Radius: " + getRadius() + "\nArea:"+ area);
}
public double area(){
return 3.14159 * (radius * radius); //calculates the area of the circle
}
}
I have tried every which way to get the Area to return and no matter what I try it will not. Everything else works fine, it prints out everything correctly but not the area. any advice?
Enter the number of shapes: 1
Enter the choice (Square, Rectangle, Circle):
1
Enter the color: red
Enter the side length of the square: 2
Shape 1:
Color: red
Side length: 2.0
Area: 0.0
You are not calculating the area , you should use area() in your print statment
System.out.println("Side length: " + getSideLength() + "\nArea: " + area());
You are printing out uninitialized variable area instead of calling the function area().
System.out.println("Side length: " + getSideLength() + "\nArea: " + area());
That should work, but you should avoid using functions and variables of the same name. getArea() would be a better function name.

Printing data using main from subclass in Java

Good morning! I have a real quick question. This is about printing the data from a subclass from an array in the main program. Please bear with me i'm rather new to this.
The program should print the Perimeter, the Area and the Average Length of a shape, which is defined in the subclass of the superclass "Shape"
But all it is printing is "Shape."
I know its just a tweak in the syntax but been trying for hours to locate where the problem is. I was wondering if any of you can give me some pointers? Thanks, your help will be much appreciated.
→ To make it easier to understand, I pasted 4 segments of my program,
Main (For collecting the user inputs and printing the results)
The Shape Superclass (Basically for defining the perimeter and area)
The Parallelogram Interface (Basically for the average of the sides lengths)
The Square Subclass (Where all the info is processed)
Main:
package shape;
import java.util.ArrayList;
import java.util.Scanner;
#author Fulltime
public class MainExecute {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Shape> list = new ArrayList<>();
Triangle t;
Square s;
Trapezoid r;
while(true){
Scanner Choice = new Scanner(System.in);
System.out.println("Enter a shape: ");
String choice = Choice.nextLine();
if(choice.equalsIgnoreCase("STOP")){
break;
}
else if(choice.equalsIgnoreCase("triangle")){
System.out.print("Enter base of triangle: ");
double base = Choice.nextDouble();
System.out.print("Enter height of triangle: ");
double height = Choice.nextDouble();
t = new Triangle(base, height);
list.add(t);
}
else if(choice.equalsIgnoreCase("square")){
System.out.print("Enter side of square: ");
double side = Choice.nextDouble();
s = new Square(side);
list.add(s);
}
else if(choice.equalsIgnoreCase("trapezoid")){
System.out.print("Enter length1 of trapezoid: ");
double length1 = Choice.nextDouble();
System.out.print("Enter length2 of trapezoid: ");
double length2 = Choice.nextDouble();
System.out.print("Enter height of trapezoid: ");
double height = Choice.nextDouble();
r = new Trapezoid(length1, length2, height);
list.add(r);
}
}
Shape q;
System.out.println("Shapes: ");
for(int i = 0; i <list.size(); i++){
q = list.get(i);
System.out.println(q.getClass().getName());
if(q.getClass().getName().equalsIgnoreCase("Triangle")){
t=(Triangle)q;
System.out.println("Perimeter: " + t.getPerimeter());
System.out.println("Area: " + t.getArea());
}
if(q.getClass().getName().equalsIgnoreCase("Square")){
s=(Square)q;
System.out.println("Perimeter: " + s.getPerimeter());
System.out.println("Area: " + s.getArea());
System.out.println("Average length of sides: " + s.getAverage());
}
if(q.getClass().getName().equalsIgnoreCase("Trapezoid")){
r=(Trapezoid)q;
System.out.println("Perimeter: " + r.getPerimeter());
System.out.println("Area: " + r.getArea());
System.out.println("Average length of sides: " + r.getAverage());
}
}
}
}
Shape Superclass
package shape;
import java.util.*;
public abstract class Shape {
public abstract double getPerimeter ();
public abstract double getArea ();
public double Perimeter;
public double Area;
public void displayInfo(){
//System.out.println("Perimeter: " + this.getPerimeter());
//System.out.println("Area: " + this.getArea());
}
}
Parallelogram Interface
package shape;
#author Fulltime
public interface Parallelogram {
public double getAverage();
}
Square Subclass
package shape;
import static java.lang.Math.*;
#author Fulltime
public class Square extends Shape implements Parallelogram {
public Square(){}
#Override
public double getPerimeter (){
Perimeter = side * 4;
return Perimeter;
}
#Override
public double getArea (){
Area = side * side;
return Area;
}
#Override
public double getAverage(){
double Sides;
Sides = (this.side + this.side + this.side + this.side) / 4;
return Sides;
}
public double side;
/**
* #return the side
*/
public double getSide() {
return side;
}
/**
* #param side the side to set
*/
public void setSide(double side) {
this.side = side;
}
public Square (double side){
this.side = side;
}
public void printSquare(){
System.out.println("The Perimeter of this shape is " + getPerimeter());
System.out.println("The Area of this shape is " + getArea());
System.out.println("The Average Length of this shape's sides is " + getAverage());
}
}
Use getSimpleName() returns the classname without the package qualification.
if(q.getClass().getSimpleName().equalsIgnoreCase("Triangle")){
}else if(..) // Also use else-if
Or you can use instanceof operator
if(q instanceof Triangle){
//logic here
}else if(..)
Now as a note this is not a good OO design using if-else for everywhere you should reconsider redesign your model.
For example make displayInformation abstract then all concrete subclasses has to override it.
abstract class Shape{
public abstract void displayInformation();
}
Triangle
public class Triangle extends Shape implements whatyouwant {
#Override
public void displayInformation(){
System.out.println("Perimeter: " + this.getPerimeter());
System.out.println("Area: " + this.getArea());
}
}
Square:
public class Square extends Shape ..{
#Override
public void displayInformation(){
System.out.println("Perimeter: " + this.getPerimeter());
System.out.println("Area: " + this.getArea());
System.out.println("Average length of sides: " + this.getAverage());
}
}
So then in your main class you don't have to code any if-else just see polimorphism magic.
for(Shape shape : list){//use enhanced loop
shape.displayInformation();
}

Categories