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.
Related
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
...
}
Why do I keep failing this test?
Test Cube(1.0, 1.0, 1.0) sets the type to "Cube",
width, length and height each to 1.0
Test feedback
Expected: Cube, 1.0, 1.0, 1.0
Yours: Rectangle, 1.0, 1.0, 1.0
I need the cube class to be able to set its type to Cube. Right now it seems to be setting itself to Rectangle. My main fills an Array of Shapes, I then have methods to count the different types of shapes according to the Type of each shape. How can I define Cube as a shape, when my rectangle class already extends shape, but I MUST have my Cube class extend rectangle. It must because I need to have access to the area as well and the length and width.
I also have a very simple interface that is implemented by my cube. It is just to find the volume. Can I somehow utilize my interface to override the type?
Can't find an answer on StackOverflow to this specific question.
Here is my Rectangle class
public class Rectangle extends Shape {
protected double width;
protected double length;
public Rectangle(double width, double length) {
super("Rectangle");
setWidth(width);
setLength(length);
}// end ctr
public final double getWidth () {return width; }
public final double getLength () {return length;}
public final void setWidth (double width) {
if (width < 0) {
System.out.println("Value could not be updated due to negative double.");
}else
this.width = width;
}// end width setter
public final void setLength (double length) {
if (length < 0) {
System.out.println("Value could not be updated due to negative double.");
}else
this.length = length;
}// end length setter
#Override
public double area() {
return length * width;
}// end area method
public double perimeter() {
return 2 * (length + width);
}// end perimeter method
#Override
public String toString() {
String str = "";
str += String.format("%10s", "Rectangle:") + " ";
str += "width: " + String.format("%.1f", width) + ", " + "length: " + String.format("%.1f", length);
str += ", " + "area: " + String.format("%.2f", area() ) + ", ";
str += "perimeter: " + String.format("%.2f", perimeter() );
return str;
}// end descriptor
}// end rect class
Here is my Cube class
public class Cube extends Rectangle implements Shape3D {
protected double height;
public Cube (double width, double length, double height) {
super(width, length);
setHeight(height);
}// end ctr
public final double getHeight () {return height;} // end get height
public final void setHeight (double height) {
if (height < 0) {
System.out.println("Value could not be updated due to negative double.");
}else
this.height = height;
}// end set height
#Override
public double volume () {
return super.area() * height;
} // end volume method
#Override
public String toString() {
String str = "";
str += String.format("%10s", "Cube:") + " ";
str += "width: " + String.format("%.1f", width) + ", " + "length: " + String.format("%.1f", length);
str += ", " + "area: " + String.format("%.2f", area() ) + ", ";
str += "perimeter: " + String.format("%.2f", perimeter() );
str += ", height: " + String.format("%.1f", height );
str += ", volume: " + String.format("%.1f", volume() );
return str;
}// end descriptor
}// end cube class
The Rectangle class comes from my Shape class,
public abstract class Shape {
protected String type;
public Shape (String type) {
setType(type);
}// end ctr
public final String getType () {return type; }
public final void setType (String type) {this.type = type;}
public abstract double area (); // end prototype
public double getArea () {return area();}
#Override
public String toString() {
String str = "";
str += type;
return str;
}// end descriptor
}// end shape class
Your cube class uses super to call rectangle's constructor which in turn calls the
Shape class's constructor with the string "Rectangle", basically as you have it, the cube constructor will not allow you to set its type of cube. You will need to explicitly use the setType method.
You could in cube's constructor add the line
this.setType("Cube");
and it should work (have not tested).
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;
}
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I write following program to invoke the toString method, but it is not working.
import java.util.Scanner;
public class findarea_class {
public static void main(String[] args)
{
findarea_class objtostring = new findarea_class(1.0,1.0);
objtostring.setelements();
}
double width;
double height;
Scanner input = new Scanner(System.in);
findarea_class()
{
}
findarea_class(double width,double height)
{
this.width = width;
this.height = height;
}
public String toString()
{
return "width is: "+this.width+" and height is: "+this.height+"\n"
+"The area is : "+getarea(width,height)+"\n"
+"The perimeter is: "+getperimeter(width,height);
}
double getarea(double width,double length)
{
double area = width * length;
return area;
}
double getperimeter(double width,double length)
{
double perimeter = (2 * length) + (2 * width);
return perimeter;
}
double getwidth()
{
System.out.println("Please the width for calculation:");
double inputwidth = input.nextDouble();
System.out.println("Width is:"+inputwidth);
return inputwidth;
}
double getheight()
{
System.out.println("Please enter the height for calculation:");
double inputheight = input.nextDouble();
System.out.println("Height is:"+inputheight);
return inputheight;
}
void setelements()
{
double newwidth;
double newheight;
newwidth = getwidth();
newheight = getheight();
System.out.println("The new area is : "+getarea(newwidth,newheight));
System.out.println("The new perimeter is `enter code here`: "+getperimeter(newwidth,newheight));
}
}
You're not calling toString(). Pass it to anything that can display it. Use:
System.out.println(objtostring.toString());
Your main method should print the object, or maybe you can put the println call in your constructor (although i'm not a big fan of that).
public static void main(String[] args)
{
findarea_class objtostring = new findarea_class(1.0,1.0);
System.out.println(objtostring);
objtostring.setelements();
}
You are trying to override the toString method of Object class. Try this one.
#Override
public String toString() {
return "width is: "+this.width+" and height is: "+this.height+"\n"
+"The area is : "+getarea(width,height)+"\n"
+"The perimeter is: "+getperimeter(width,height);
}
and call it as objectName.toString();. In this case use something like this.objtostring.toString();