Printing data using main from subclass in Java - 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();
}

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!

Store objects in ArrayList and output Object description

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();
}

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.

Carpet calculator error calling a class?

The assignment goes as stated:
The problem
The westfield carpet company has asked you to write an application that calculates the price of carpeting for rectangular rooms. To calculate the price, you multiply the area of the floor(width times length) by the price per square foot of carpet. For example, the area of floor that is 12 feet long and 10 feet wide is 120 square feet. To cover that floor with carpet that costs $8 per square foot would cost $960 (12x10x8=960)
First, you should create a class named RoomDimension that has two Feields: one for the lenght of the room and one for the width. The RoomDimension class should have a method that returns the area of the room (the area of the room is the room's length multiplied by the room's width).
Next, you should create a RoomCarpet class that has a RoomDimension object as a field. It should also have a field for the cost of the carpet per square foot. The RoomCarpet class should have a method that returns the total cost of the carpet.
Once you have written these classes, use them in an application that asks the user to enter the dimensions of a room and the price per square foot of the desired carpeting. The application should display the total cost of the carpet.
The code I have below can't seem to run due to an error in the 31st line of the MainProgram
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
final double CARPET_PRICE_PER_SQFT = 8.0;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Display intro.
System.out.println("This program will display the "
+ "carpet cost of a room." + "\nPlease enter the room's "
+ "dimension in feet.");
// Get the length of the room.
System.out.print("Enter the length of room: ");
double length = keyboard.nextDouble();
// Get the width of the room.
System.out.print("Enter the width of room: ");
double width = keyboard.nextDouble();
//close keyboard
keyboard.close();
****// Create RoomDimension and RoomCarpet objects.
CarpetCalculatorProgram calculatorProgram = new CarpetCalculatorProgram();
RoomDimension dimensions = calculatorProgram.new RoomDimension(length,
width);
RoomCarpet roomCarpet = calculatorProgram.new RoomCarpet(dimensions,
CARPET_PRICE_PER_SQFT);****
// Print the object calling the toString
System.out.println(roomCarpet);
}
}
Here are the other classes for the code:
Room Dimension
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class RoomDimension {
private double length;
private double width;
public RoomDimension(double length, double width) {
super();
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getArea() {
return length * width;
}
#Override
public String toString() {
return "RoomDimension [length=" + length + ", width=" + width + "]";
}
}
Room Carpet
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class RoomCarpet {
private RoomDimension roomDimensions;
private double costOfCarpet;
public RoomCarpet(RoomDimension roomDimensions, double costOfCarpet) {
super();
this.roomDimensions = roomDimensions;
this.costOfCarpet = costOfCarpet;
}
public double getTotalCost() {
return costOfCarpet * roomDimensions.getArea();
}
#Override
public String toString() {
return "RoomCarpet [roomDimensions=" + roomDimensions
+ ", costOfCarpet=" + costOfCarpet + ", "
+ "total cost=" + getTotalCost() + "]";
}
}
The error I get when I paste all the things into my IDE is
CarpetCalculatorProgram cannot be resolved to a type
Assuming that there are no classes you didn't post:
There is no CarpetCalculatorProgram class and there are no inner RoomDimension / RoomCarpet classes in there. RoomDimension is actually an independent top level class. The code must either be
// Create RoomDimension and RoomCarpet objects.
RoomDimension dimensions = new RoomDimension(length,
width);
RoomCarpet roomCarpet = new RoomCarpet(dimensions,
CARPET_PRICE_PER_SQFT);
instead of using new EnclosingClass().new InnerClass() syntax. OR
// Create RoomDimension and RoomCarpet objects.
CarpetCalculatorProgram calculatorProgram = new CarpetCalculatorProgram();
CarpetCalculatorProgram.RoomDimension dimensions = calculatorProgram.new RoomDimension(length,
width);
CarpetCalculatorProgram.RoomCarpet roomCarpet = calculatorProgram.new RoomCarpet(dimensions,
CARPET_PRICE_PER_SQFT);
AND the two classes moved into the CarpetCalculatorProgram class:
public class CarpetCalculatorProgram {
public class RoomDimension {
...
}
public class RoomCarpet {
...
}
}
Well my code is working properly, see if it helps you.
import java.util.Scanner;
class RoomDimension{
private int length;
private int width;
public RoomDimension(int length, int width){
this.length= length;
this.width= width;
}
public int Area(){
int area= this.length* this.width;
return area;
}
public int getlength(){
return this.length;
}
public int getwidth(){
return width;
}
}
class RoomCarpet{
private RoomDimension RD;
private int costperSq;
public RoomCarpet(RoomDimension RD, int costperSq){
this.RD= RD;
this.costperSq= costperSq;
}
public int TotalCost(){
return this.costperSq* RD.Area();
}
}
[Main]
class Main{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("enter the length the room");
int L= sc.nextInt();
System.out.println("enter the width the room");
int W= sc.nextInt();
RoomDimension RD= new RoomDimension(L, W);
System.out.println("enter how much the carpet costs per sq");
int cost= sc.nextInt();
RoomCarpet RC= new RoomCarpet(RD, cost);
System.out.println("total cost of the carpet will be= "+RC.TotalCost());
}
}

Categories