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;
}
Related
I'm trying to create a toString method in a Box class to call in a BoxTest class. I've set up the methods I want to call (getLength, getHeight, getWidth, calculateArea, calculateVolume), which work fine by themselves, but I'm unsure how to use them when calling toString.
Here is a pastebin (http://pastebin.com/Ex520ST6) of my current code.
Box
public class Box
{
private double length = 1.0;
private double width = 1.0;
private double height = 1.0;
public Box(double length, double width, double height) // constructor with thrown exceptions
{
if (length <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
if (width <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
if (height <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.length = length;
this.width = width;
this.height = height;
}
public void setLength(double length)
{
if (length <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.length = length;
System.out.println("The new length is: " + length);
}
public double getLength()
{
System.out.println("The length is: " + length);
return length;
}
public void setWidth(double width)
{
if (width <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.width = width;
System.out.println("The new width is: " + width);
}
public double getWidth()
{
System.out.println("The width is: " + width);
return width;
}
public void setHeight(double height)
{
if (height <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.height = height;
System.out.println("The new height is: " + height);
}
public double getHeight()
{
System.out.println("The height is: " + height);
return height;
}
public double calculateArea()
{
double area = (double) (2*length*width + 2*length*height + 2*width*height);
System.out.println("The area is: " + area);
return area;
}
public double calculateVolume()
{
double volume = (double) length*width*height;
System.out.println("The volume is: " + volume);
return volume;
}
public String toString()
{
return String.format("The length is %f, the width is %f, the height is %f, the area is %f, the volume is %f,");
}
}
BoxTest
public class BoxTest
{
public static void main (String[] args)
{
Box[] boxes = new Box[4];
boxes[0] = new Box(1.0,2.0,3.0);
boxes[1] = new Box(4.0,5.0,6.0);
boxes[2] = new Box(1.0,7.0,8.0);
boxes[3] = new Box(1.0,9.0,9.0);
for (Box theBoxes : boxes)
{
System.out.printf(theBoxes.getLength(),theBoxes.getWidth(),theBoxes.getHeight(),theBoxes.calculateArea(),theBoxes.calculateVolume().toString());
}
boxes[3].setLength(11.0); // debug
}
}
Am I on the right track, generally
Should I be using "%s" specifier in the toString heading
Do I still need a format specifier in the printf, and if so, should it be %s or %f, as my methods are type double.
Thank you!
The toString() override should return a String with the values themselves and not rely on external use of System.out.printf() (The method can of course be used within the class, but the class should return a fully formatted String and not one that contains formatters like %s). An example implementation is as follows.
class Animal {
public String name;
public int numlegs;
public double weight;
// ...
#Override
public String toString() {
return String.format("Animal, name: %s, legs: %d, weight: %d", name, numLegs, weight);
}
}
You would then retrieve the full String representation of the object simply by calling the toString() method.
It is encouraged to use printf() rather than large scale String concatenation as it makes for cleaner code (IMO at least).
Side-notes:
Your toString() method calls printf() but doesn't provide the values that should replace the formatters in the format String.
Calls to printf() should have the format String as the first argument and the values as the remaining arguments.
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.
package homeWork;
public class ShoppingBag {
private int items;
private float totalRetailCost;
private float taxRate;
public ShoppingBag(float taxRate){
this.taxRate = taxRate;
items = 0;
totalRetailCost = 0.0f;
}
// Transformer
public void place(int numItems, float theCost){
items = items += numItems;
totalRetailCost += (numItems * theCost);
}
public int getItems(){
return items;
}
public float getRetailCost(){
return totalRetailCost;
}
public float getTotalCost(){
return totalRetailCost + (1 + taxRate);
}
public String toString(){
String result = "The bag contains " + items + " items";
result += "The retail cost of items is" + totalRetailCost;
result += "The total cost = " + getTotalCost();
return result;
}
}
package homeWork;
import java.util.*;
public class MainClass {
public static void main(String[] args){
Scanner conIn = new Scanner(System.in);
ShoppingBag sb = new ShoppingBag(0.06f);
int count = 0;
float cost = 0.0f;
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
while(count != 0){
System.out.print("Enter cost: ");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
}
}
}
I have tried all that I have found on here to return result after completion of input. Ive done what my book has shown me to do but I am not getting a result. Just a nudge in the right direction would be helpful.
You are no printing the object anywhere. Print the object
System.out.print(sb);
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());
}
}
First off sorry about the title I could not think how I should title this. The prompt of the assignment had us calculate the volume and surface area of a pyramid and prism with three different classes(two classes with constructors and one test class), and as the title states I keep getting zero.
Here is the prism class:
public class Prism
{
double l;
double w;
double h;
public Prism(double intL, double intW, double intH)
{
double l = intL;
double w = intW;
double h = intH;
}
public double getPrismVolume()
{
return l*w*h;
}
public double getPrismSurfaceArea()
{
return 2*((l*w)+(h*l)+(h*w));
}
}
Here is my Pyramid class:
public class Pyramid
{
double b;
double h;
public Pyramid(double intB, double intH)
{
double b = intB;
double h = intH;
}
public double getPyramidVolume()
{
return (1.0/3.0)*Math.pow(b,2)*h;
}
public double getPyramidSurfaceArea()
{
return Math.pow(b,2)+(2*b*h);
}
}
Here is my test class:
import java.util.*;
public class GeometryTest
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter the length of the prism: ");
String answer1 = myScanner.nextLine();
double length = Double.parseDouble(answer1);
System.out.print("Enter the width of the prism: ");
String answer2 = myScanner.nextLine();
double width = Double.parseDouble(answer2);
System.out.print("Enter the height of the prism: ");
String answer3 = myScanner.nextLine();
double height = Double.parseDouble(answer3);
System.out.print("Enter the pyramid's base: ");
String answer4 = myScanner.nextLine();
double base = Double.parseDouble(answer4);
System.out.print("Enter the pyramid's height: ");
String answer5 = myScanner.nextLine();
double pyramidHeight = Double.parseDouble(answer5);
Pyramid aPyramid = new Pyramid(base,pyramidHeight);
Prism aPrism = new Prism(length,width,height);
System.out.println("The prism's volume is: " + aPrism.getPrismVolume());
System.out.println("The prism's surface area is: " + aPrism.getPrismSurfaceArea());
System.out.println("The pyramid's volume is: " + aPyramid.getPyramidVolume());
System.out.println("The pyramid's surface area is: " + aPyramid.getPyramidSurfaceArea());
}
}
Your constructors are declaring local variables and ignoring the instance variables. The instance variables are left uninitialized, so Java initializes them to their default value, 0.
E.g. change
double l = intL;
to
l = intL;
so l will resolve to the instance variable name.
You are hiding your class level fields with variable shadows;
public Prism(double intL, double intW, double intH)
{
// double l = intL;
// double w = intW;
// double h = intH;
this.l = intL;
this.w = intW;
this.h = intH;
}
and the same problem in Pyramid -
public Pyramid(double intB, double intH)
{
// double b = intB;
// double h = intH;
this.b = intB;
this.h = intH;
}