Carpet calculator error calling a class? - java

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

Related

Is there any way I can rewrite my methods better?

I'm not entirely sure if there is an easier answer to this question and I'm thinking to hard about it or what, but I'm currently programming a rectangular block program to practice Java. It's structured to have 4 methods: getInput, volBlock, saBlock, and display, and I want to use only local variables for these methods. Is there a way that I can utilize getInput to accept and return a single double from the user and if so, how can I use that input in my other methods?
I constructed this code, which uses local variables in getInput() and then passes those values to other methods, but I couldn't figure out a display method so I hard coded it into the calculation methods themselves.
Here is that code:
import java.util.*;
public class Block {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice = "Y";
while (choice.equals("Y")){
getInput();
System.out.println("Would you like to do another calculation?(Y/N): ");
choice = in.next().toUpperCase();
}
System.out.println("Program now ending...");
}
public static void getInput() {
double l, w, h;
Scanner fin = new Scanner(System.in);
System.out.println("Please enter the length, width, and height in that order: ");
l = fin.nextDouble();
w = fin.nextDouble();
h = fin.nextDouble();
volBlock(l, w, h);
surfaceAreaBlock(l,w,h);
}
public static void volBlock(double length, double width, double height) {
double volume;
volume = length * width * height;
System.out.println("The volume is: " + volume);
}
public static void surfaceAreaBlock (double l, double w, double h) {
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
System.out.println("The surface area is: " + surfaceArea);
}
}
I'm sorry if this question is kind of scrambled, I am having a hard time figuring all of this out. I'm quite new to Java.
Any help is appreciated, thank you!
If you're practicing java, you should probably familiarize yourself more with object oriented programming before you go any further, because your code leads me to believe that you're more used to procedural languages (e.g. C, C++, etc). Java doesn't rely on having several static helper methods in its main; the preferred approach is to construct a few classes that perform these calculations for you, and you use the results created by these functions for your basic input/output, which is normally what main is used for.
I implemented a block class to demonstrate what I mean:
public class Block {
private double length;
private double width;
private double height;
public Block(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * length * (height + width) + height * width;
}
/* This is the "display" method that you want */
public String toString() {
return "The volume is: " + getVolume() + "\n"
"The surface area is: " + getSurfaceArea();
}
}
using the Block class, your main becomes much more simple:
public static void main() {
Scanner in = new Scanner(System.in);
char choice = 'y';
do {
System.out.print("Please enter the dimensions of the block: ");
double length = in.nextDouble();
double width = in.nextDouble();
double height = in.nextDouble();
Block block = new Block(length, width, height);
System.out.println(block);
System.out.print("continue (y/n)? ");
choice = in.nextLine.toLowerCase().charAt(0);
} while (choice == 'y');
}
If you return the values from your getInput(), volBlock() and surfaceAreaBlock() methods you might be able to structure the rest as you want to.
For instance surfaceAreaBlock becomes:
public static double surfaceAreaBlock (double l, double w, double h){
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
return surfaceArea;
}
and then when you call surfaceAreaBlock you can do this:
public static void main(String[] args) {
...
double surfaceArea = surfaceAreaBlock();
// Do something with the surface area in this method
...
}

How do I obtain the final result for floorboard calculation?

Let's say you've calculated both the length and width of a floorboard and worked out the room area, how would you go about multiplying 10% to the room area to work out the wastage in order to obtain the final total area of the floorboard?
This is what I have done so far:
import java.util.Scanner;
class Floor1 {
public static void floor1(String[] args) {
obtainLength();
obtainWidth();
obtainRoomArea(length, width);
obtainFinalResult();
System.exit(0);
}
public static void obtainLength ()
Scanner in = new Scanner(System.in);
System.out.println("Enter length of room:");
float length = in.nextFloat();
}
public static void obtainWidth ()
Scanner in = new Scanner(System.in);
System.out.println("Enter width of room:");
float width = in.nextFloat();
}
public static void obtainRoomArea (float Length, float Width){
float RoomArea = RoomArea(Length, Width);
System.out.println("Area of room is:" + RoomArea);
}
public static void obtainFinalResult()
final double total = 0.1;
wastage =(float RoomArea* final double total);
System.out.println("The total calculations including wastage is:" + wastage);
}
}
I am only retrieving the area of the room. I'm unable to retrieve the final results. Could you please show me where I'm going wrong with examples please? Many thanks!!

Not able to getting data from one class to another using *.get*()

I have two classes RoomDimension & RoomCarpet. Then I have a program that calls these two classes but I am having a problem with the RoomCarpet Class when I try and get a TotalCost for the carpet. It gives me this error when I run CarpetCalculator
(Exception in thread "main" java.lang.NullPointerException
at RoomCarpet.getTotalCost(RoomCarpet.java:49)
at CarpetCalculator.main(CarpetCalculator.java:44)
java:44, this location is the system.out.print at the end that calls the getTotalCost,
when I try and call the getTotalCost under the RoomCarpet class. I think it has to do with the size.getArea() (when I call it). Below is the code for all classes. Thank all of you for any help.
RoomDimension:
public class RoomDimension {
private double length;
private double width;
public RoomDimension(double len, double w){
length = len;
width = w;
}
public void setLength(double len){
length = len;
}
public void setWidth(double w){
width = w;
}
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
public double getArea(){
return length * width;
}
public String toString(){
String str = "The length you entered was " + length
+ " and the width you entered was " + width;
return str;
}
}
RoomCarpet:
public class RoomCarpet{
private RoomDimension size;
private double carpetCost;
public RoomCarpet (double cost){
carpetCost = cost;
}
public void setCarpetCost(double cost){
carpetCost = cost;
}
public double getCarpetCost(){
return carpetCost;
}
public double getTotalCost(){
return size.getArea() * carpetCost;
}
public String toString(){
String str = "\nYour total area for your room is " + size.getArea()
+ "\nThe cost of your carpet per square foot is " + carpetCost;
return str;
}
}
CarpetCalculator:
import java.util.Scanner; // Needed for the Scanner class
/**
* This program demonstrates the RoomDimension & RoomCarpet classes.
*/
public class CarpetCalculator {
public static void main(String[] args){
double length; // hold room length
double width; // hold room width
double cost; // hold carpet cost
Scanner keyboard = new Scanner(System.in);
System.out.print("What is your rooms length? ");
length = keyboard.nextDouble();
System.out.print("What is your rooms width? ");
width = keyboard.nextDouble();
System.out.print("What is the cost of your carpet per square foot? ");
cost = keyboard.nextDouble();
RoomDimension testDimension = new RoomDimension(length, width);
RoomCarpet testCarpet = new RoomCarpet(cost);
System.out.println(testDimension);
System.out.println(testCarpet);
System.out.println("Which means your total cost to carpet the room is " + testCarpet.getTotalCost());
}
}
You need to initialize the size variable in RoomCarpet class. You can use setter method or pass through constructor.
try this :
public class RoomCarpet {
private RoomDimension size;
private double carpetCost;
public RoomCarpet (double cost){
carpetCost = cost;
}
public RoomCarpet (double cost,RoomDimension size){
carpetCost = cost;
this.size = size;
}
public void setCarpetCost(double cost){
carpetCost = cost;
}
public double getCarpetCost(){
return carpetCost;
}
public RoomDimension getSize() {
return size;
}
public void setSize(RoomDimension size) {
this.size = size;
}
public double getTotalCost(){
if(size != null) {
return size.getArea() * carpetCost;
}
else {
System.out.println("error size is not define");
return 0;
}
}
public String toString(){
String str = "\nYour total area for your room is " + size.getArea()
+ "\nThe cost of your carpet per square foot is " + carpetCost;
return str;
}
}
That is because you never initialize in your RoomCarpet the size attribute. You should pass a RoomDimension object in the RoomCarpet constructor:
public RoomCarpet (RoomDimension size, double carpetCost){
this.size = size;
this.carpetCost = carpetCost;
}

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

I'm trying to call a double variable from one method into another

How do i call the length and width variable into the getArea method without creating a private variable in the class, the way I'm doing it is causing the method to run again after its already ran once. I really don't like it this way but thats the way the professor wants it done to simulate the times before "object oriented programming"
/*This program allows the user to enter the length and widtch and receive the area
of the rectangle*/
import java.util.Scanner;
public class theRectangleCompany
{
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getLength();
getWidth();
getArea();
}
public static double getLength()
{
double length;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the length ");
length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
double width;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the width ");
width = keyboard.nextDouble();
return width;
}
public static void getArea()
{
double length = getLength();
double width = getWidth();
double area = width * length;
System.out.println("The area of the Rectangle is: " +area);
}
}
Why are you calling getLength() and getWidth() from the main method. Just call getArea()
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
You could make the getArea function take parameters, and use the function calls to the other two functions as the parameters:
getArea(getLength(), getWidth());
public static void getArea(double length, double width) { ... }
changes are here:
/*This program allows the user to enter the length and widtch and receive the area
of the rectangle*/
import java.util.Scanner;
public class theRectangleCompany
{
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
public static double getLength()
{
double length;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the length ");
length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
double width;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the width ");
width = keyboard.nextDouble();
return width;
}
public static void getArea()
{
double length = getLength();
double width = getWidth();
double area = (width * length);
System.out.println("The area of the Rectangle is: " +area);
}
}
Not sure if this is what you want:
public static void getArea()
{
System.out.println("The area of the Rectangle is: " + (getLength() * getWidth()));
}
You'd also need to change the main method to exclude the getLength() and getWidth():
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
An variant to the above is something like
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea(getLength(),getWidth());
}
public static void getArea(double length, double width)
{
System.out.println("The area of the Rectangle is: " + (length * width));
}

Categories