Using toString correctly - java

I am working on some home work and cannot figure out how to call the toString methods from the Point, Square and Cube classes to print out. I know it has to be something stupid, I think I am just toast and my mind is spent. Right now I have ??? in place where the toSting methods should go. Have tried every combination ("class".toString, etc) I can think of. Can anyone tell me where I am messing up? Thanks!!
import javax.swing.JOptionPane;
public class InheritanceTest {
public static void main(String args[]){
// Declare variables
String xString = null;
String yString = null;
String sideString = null;
int x = 0;
int y = 0;
int sideLength = 0;
try{
xString = JOptionPane.showInputDialog("Enter x coordinate:");
x = Integer.parseInt(xString);
yString = JOptionPane.showInputDialog("Enter y coordinate:");
y = Integer.parseInt(yString);
sideString = JOptionPane.showInputDialog("Enter side of Square:");
sideLength = Integer.parseInt(sideString);
} // End try
catch(NumberFormatException e){
JOptionPane.showMessageDialog( null,"The value you entered is not a valid number. Please try again",
"Error", JOptionPane.ERROR_MESSAGE);
} // End catch
JOptionPane.showMessageDialog(null, "Point: \n" +????????, "Results", JOptionPane.INFORMATION_MESSAGE);
} // End main
}// End Class
class Point{
//Declare variables
private int x;
private int y;
// Point constructor
Point(int xCoordinate,int yCoordinate){
x = xCoordinate;
y = yCoordinate;
}// End Point Constructor
// Accessor to return x coordinate
public int getX(){
return x;
}// End getX method
// Accessor to return y coordinate
public int getY(){
return y;
}// End getY method
// Format and display coordinates
public String toString(){
return "Corner = [" + x + "," + y + "]\n";
}// End toString
}// End Point Class
abstract class Square extends Point{
//Declare variables
private double sideLength;
// Square constructor
Square(int x, int y, double s){
super(x, y);
sideLength = s;
} // End Square constructor
// Accessor to return side length
public double getSide(){
return sideLength;
} // End getSide
// Method to calculate area of square
public double area(){
return sideLength * sideLength;
} // End area method
// Method to calculate perimeter of square
public double perimeter(){
return 4 * sideLength;
} // End perimeter method
// Format and display the square
public String toString(){
return super.toString() + "Side length is: " + sideLength + "\n" +
"Area is: " + area() + "\n" + "Perimeter is: " + perimeter();
} // End toString
}// End Square Class
abstract class Cube extends Square{
// Declare variable
double depth;
// Cube constructor
public Cube(int x, int y, double s, double z){
super(x, y, s);
depth = z;
} // End Cube constructor
// Method to calculate area of cube
public double area(){
return 6 * super.area();
} // End Area
// Method to calculate volume of cube
public double volume(){
return super.area() * depth;
} // End volume
// Format and display the cube
public String toString(){
return "Depth is: " + depth + "\n" + "Area is: " + area() + "\n" + "Volume is: " + volume();
} // End toString
} // End Cube class

You don't invoke the toString() method from a Class, you invoke it from an object (i.e. an instance of that Class). It's obj.toString() where obj is an instance of Point, Square or Cube (or any other class).
I don't see you instantiating any objects of those classes, though. You need to create an instance of the class before you can invoke an instance-based method like toString().
Point myPoint = new Point(x, y);
String pointString = myPoint.toString();

Well you need to create an instance of the class that you want to work with first, for example:
Square s = new Square(10, 10, 2.0);
System.out.println(s.toString());

new Point(x,y).toString()
toString() is a method of the Point class. You need to instantiate it first with x and y coordinates then call its toString() method.

JOptionPane.showMessageDialog(null,
"Point: \n" + new Point(x, y).toString,
"Results",
JOptionPane.INFORMATION_MESSAGE);

Related

Radius Variable Isn't Being Passed From Constructor

I'm supposed to be using a constructor to accept the radius of a circle as an argument then using various accessor and mutator methods to display the area, circumference, and diameter. When I input the value for radius, say 4, it says that the radius and all other values (area, circumference, diameter ) are 0.0. I'm new to java and wanna know what I'm missing.
// import scanner to read keyboard input
import java.util.Scanner;
class CircleCalculator
{
private double radius;
public CircleCalculator(double r)
{
radius = r;
}
public static void main(String[] args)
{
// declare the variable keyboard that can reference an object of the scanner class
// create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
double r, a, d, c;
CircleData circledata = new CircleData();
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() +" units squared\n" +
"\tDiameter: " + circledata.getDiameter() +" units\n" +
"\tCircumference: " + circledata.getCircumference() +" units\n");
}
public static class CircleData //create class for mutator and accessor methods
{
Scanner keyboard = new Scanner(System.in);
double r = keyboard.nextDouble();
CircleCalculator setRadius = new CircleCalculator(r);
final double pi = 3.1415;
private double radius, area, diameter, circumference;
private double getRadius()
{
return radius;
}
private double getArea()
{
area = pi * radius * radius;
return area;
}
private double getDiameter()
{
diameter = 2 * radius;
return diameter;
}
private double getCircumference()
{
circumference = 2 * pi * radius;
return circumference;
}
}
}
Gives:
Welcome to Cam's Magic Circle Calculator!
Enter the radius of your circle
4
The measurements of a circle with the radius 0.0 are:
Area: 0.0 units squared
Diameter: 0.0 units
Circumference: 0.0 units
Your current code is confused because of the nesting of your classes. I recommend following good code practices by separating them out into their own class files. Let CircleData handle the actual circle data and calculation and make CircleCalculator your overall program sequence logic.
CircleCalculator
import java.util.Scanner;
public class CircleCalculator
{
public static void main(String[] args)
{
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
Scanner keyboard = new Scanner(System.in);
CircleData circledata = new CircleData(keyboard.nextDouble());
keyboard.close();
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() +" units squared\n" +
"\tDiameter: " + circledata.getDiameter() +" units\n" +
"\tCircumference: " + circledata.getCircumference() +" units\n");
}
}
CircleData (in separate file so methods are now public)
public class CircleData
{
final double pi = 3.1415;
private double radius, area, diameter, circumference;
public CircleData(double radius) {
this.radius = radius;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
area = pi * radius * radius;
return area;
}
public double getDiameter()
{
diameter = 2 * radius;
return diameter;
}
public double getCircumference()
{
circumference = 2 * pi * radius;
return circumference;
}
}
Because radius fields from CircleCalculator and CircleData classes are two different fields. So, you cannot use the radius of CircleCalculator from CircleData because CircleData contains such field already.
CircleData actually shouldn't have the Scanner field, it breaks SRP https://en.wikipedia.org/wiki/Single-responsibility_principle.
I'd recommend writing it this way:
class CircleCalculator {
public static void main(String[] args) {
// declare the variable keyboard that can reference an object of the scanner class
// create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
CircleData circledata = new CircleData(keyboard.nextDouble());
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() + " units squared\n" +
"\tDiameter: " + circledata.getDiameter() + " units\n" +
"\tCircumference: " + circledata.getCircumference() + " units\n");
}
public static class CircleData //create class for mutator and accessor methods
{
final double pi = 3.1415;
private final double radius;
public CircleData(double radius) {
this.radius = radius;
}
private double getRadius() {
return radius;
}
private double getArea() {
return pi * radius * radius;
}
private double getDiameter() {
return 2 * radius;
}
private double getCircumference() {
return 2 * pi * radius;
}
}
}
The radius variable isn't being passed from constructor because you have defined the constructor in the CircleCalculator class but the methods for calculating the area, circumference, etc using the radius variable value are in different class.
CircleCalculator setRadius = new CircleCalculator(r);
Here, though setRadius has the value which user has entered but it's not being used.
CircleData circledata = new CircleData();
Here, the circledata is referencing nothing. The method calls
circledata.getRadius() , circledata.getArea() , circledata.getDiameter() , circledata.getCircumference() are actually returning the default value of double that is 0.0 because the radius variable default value is 0.0
Also, there should be only one public class in a class file whose name should match the class file name and that public class should have the public static void main(String[] args) method.

Designing a class named Triangle in Java [duplicate]

This question already has answers here:
Constructor cannot be applied to given types?
(3 answers)
Closed 2 years ago.
Design a class named Triangle that extends GeometricObject. This class contains:
a. Three double data fields named side1, side2, and side3 with default values 1.0 to denote three sides of the triangle.
b. A no-arg constructor that creates a default triangle.
c. A constructor that creates a triangle with the specified side1, side2 and side3.
d. The accessor methods for all three data fields.
e. A method named getArea() that returns the area of this triangle.
f. A method named getPerimeter() that returns the perimeter of this triangle.
g. A method named toString() that returns a string description for the triangle.
The formula for computing the area of the triangle is:
s = (side1 + side2 + side3)/2;
area = s(s – side1) (s – side2) (s – side3)
The toString() method is implemented as follows:
return “Triangle: side1 = “ + side1 + “side2 = “ + side2 + “side3 = “ + side3;
Write a test program that prompts the user to enter three sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input. The program should display the area, perimeter, color, and true or false to indicate whether it is filled or not.
I have tried this question and the codes are as below, but there is an error in the Triangle class and i do not know how to fix it.
//Triangle Class
public class Triangle extends GeometricObject
{
private double side1 = 1.0;
private double side2 = 1.0;
private double side3 = 1.0;
public Triangle()
{
}
public Triangle(double side1, double side2, double side3)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getSide1()
{
return side1;
}
public double getSide2()
{
return side2;
}
public double getSide3()
{
return side3;
}
public void setSide1(double side1)
{
this.side1 = side1;
}
public void setSide2(double side2)
{
this.side2 = side2;
}
public void setSide3(double side3)
{
this.side3 = side2;
}
public double getArea()
{
double area,s;
s = (side1+side2+side3)/2;
area = Math.sqrt(s * (s- side1) * (s - side2) * (s - side3));
return area;
}
public double getPerimeter()
{
return side1 + side2 + side3;
}
public String toString()
{
return " Triangle: Side 1 = " + side1 + " Side 2 = " + side2
+ " Side 3 = " + side3;
}
}
//GeometricObject Class
public class GeometricObject
{
protected String color = "white";
protected boolean filled;
public GeometricObject(String color, boolean filled)
{
this.color = color;
this.filled = filled;
}
//getColor()
public String getColor()
{
return color;
}
//setColor
public void setColor(String color)
{
this.color = color;
}
//isFilled
public boolean isFilled()
{
return filled;
}
//setFilled
public void setFilled(boolean filled)
{
this.filled = filled;
}
}
//Test Program
public class Lab82
{
private double side1 = 1.0;
private double side2 = 1.0;
private double side3 = 1.0;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter three sides of the Triangle");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
System.out.println("Enter the color of the Triangle");
String color = input.next();
System.out.println(" Is the Triangle filled? Reply with 'True' or 'False' ");
String filled = input.next();
Triangle triangle = new Triangle(side1, side2, side3);
System.out.println("The Triangle Sides are \n side 1: " + triangle.getSide1() + "\n Side 2: " + triangle.getSide2() + "\n Side 3: " + triangle.getSide3());
System.out.println("The Triangle's Area is " + triangle.getArea());
System.out.println("The Triangle's Perimeter is "+ triangle.getPerimeter());
System.out.println("The Triangle's Color is " + triangle.getColor());
System.out.println("Is the Triangle filled? " + triangle.isFilled());
}
}
The errors that i get are these :
When your class is extending another which doesn't have a default (no-argument) constructor, you should tell java how to construct its parent class when constructing an instance of the child class. In your case, java doesn't know what to give for color and filled to the parent constructor.
You should call the parent constructor in all of the child class's constructors usingsuper keyword like this:
public class Triangle extends GeometricObject
{
// ...
public Triangle()
{
super(someColor, someFilled);
}
// ...
}

add object directly in a array

I have written a object for a school assignment. now i'm trying to add it to an array so i can add multiple boxes.
my main
String name;
double userInputLength;
double userInputWidth;
double userInputHeight;
// initialise a scanner to be able to read the user input
Scanner reader = new Scanner(System.in);
// ask the user for input
System.out.print ("Enter the name of your box: ");
// read this input
name = (reader.nextLine());
// ask the user for input
System.out.print ("Enter the length of your box: ");
// read this input
userInputLength = (reader.nextDouble());
// ask the user for input
System.out.print ("Enter the width of your box: ");
// read this input
userInputWidth = (reader.nextDouble());
// ask the user for input
System.out.print ("Enter the height of your box: ");
// read this input
userInputHeight = (reader.nextDouble());
Block blockOne = new Block(name, userInputLength, userInputWidth, userInputHeight);
System.out.println( blockOne.showBoxAsString());
My object
package model;
import java.util.ArrayList;
import java.util.List;
public class Block {
// name variable of the figure
private String name;
// dimension variable of the figure
private double blockWidth;
private double blockHeight;
private double blockLength;
public Block() {
}
// form a block
public Block(String N, double L, double W, double H){
this.name = N;
this.blockLength = L;
this.blockWidth = W;
this.blockHeight = H;
}
// set the name
public void setBlockName(String N){ this.name = N; }
// set the name
public String getBlockName(){ return this.name; }
//set length method
public void setLength(double L)
{
this.blockLength = L;
}
//get length method
public double getLenght(){
return this.blockLength;
}
//set width method
public void setWidth(double W)
{
this.blockLength = W;
}
//get width method
public double getWidth(){
return this.blockWidth;
}
//set height method
public void setHeight(double H)
{
this.blockLength = H;
}
//get height method
public double getHeight(){
return this.blockHeight;
}
// method to calculate the surface of the shape (in this situation its a box)
public double calcSurfaceBox(){
// the formula to calculate the surface of the box is length times the width
double surface = 2 * (this.blockHeight * this.blockWidth) +
2 * (this.blockLength * this.blockHeight) +
2 * (this.blockWidth * this.blockLength) ;
// return the calculated value of surface
return surface;
}
// method to calculate the volume of the shape (in this situation it's a box)
public double calcVolumeBox(){
// the formula to calculate the volume is length times width times height
double volume = this.blockLength * this.blockWidth * this.blockHeight;
// return the calculated value of volume
return volume;
}
// a method to print a string to show the user the size of the shape (in this case a box.)
public String showBoxAsString(){
return String.format( "The box has a name: " + getBlockName() + "\n" +
"The box has a Length of: " + getLenght() + "\n" +
"The box has a Width of: " + getWidth() + "\n" +
"The height of the box is: " + getHeight());
}
}
i searched for multiple solutions but i can't figure it out. Is there anyone that could give me some tools or an idea?
my goal is to make my main code as clean as possible. so if anyone got an idea how i can simplify my main code that would be awesome.
Initialise an array of Block Objects
Block blocks[] = new Block[length];
To access each object use blocks[index]
Note: The array elements here store the reference variables to the object
Edit: index here means a block object perhaps blockOne

Interface and Inheritance compile time error

I have written a short program that uses inheritances and interface relationships to calculate the area and the perimeter of user selected shapes. I receive a compile time error when I attempt to compile the following classes.
Class Square
public class Square extends Quadrilateral
{
double side1 =this.side1;
double side2 = this.side2;
double perimeter = this.perimeter;
double area = this.area;
Square(double instanceSide1, double instanceSide2) {
side1 = instanceSide1;
side2 = instanceSide2;
}
#Override
public double area()
{
area = side1 *side2;
return area;
}
#Override
public double perimeter() //math equation for determing perimeter
{
this.perimeter = (side1 * 2) + (side2 * 2) ;
return perimeter;
}
}
Here is my Quad class
public abstract class Quadrilateral implements Polygon{
}
Here is the Polygon Class
public interface Polygon {
abstract void area();
abstract void perimeter();
}
Here is the Tester Class that I've built to run the code.
public static void main(String[] args) //Constructor initalizing main class
{
int numberSides;
int length;
int base;
Scanner sides = new Scanner(System.in); //Initializing Scanner Class
/**
* Do/while loop for selecting a 3 or 4 sided object
*/
do
{
System.out.println("Do you want a 3 or 4 sided shape? (Type either "
+ "3 or 4).");
numberSides = sides.nextInt();
} while (numberSides < 3 || numberSides > 4);
if (numberSides == 3) {
System.out.println("How long are the sides that are the same lenth?");
length = sides.nextInt();
System.out.println("How wide is the base? (whole numbers");
base = sides.nextInt();
IsoscelesTriangle Isoc = new IsoscelesTriangle(length, base);
System.out.println("The area of the isocolese triangle is: " + Isoc.area());
System.out.println("The perimeter of the isocolese triangle is: " + Isoc.perimeter());
} else {
System.out.println("How long are the sides are the same?");
length = sides.nextInt();
System.out.println("How wide is the base?");
base = sides.nextInt();
if (length == base) {
Square Quad = new Square(length, base);
System.out.println("The area of the square is: " + Quad.area());
System.out.println("The perimeter of the square is: " + Quad.perimeter());
} else {
Rectangle Quad = new Rectangle(length, base);
System.out.println("The area of the rectangle is: " + Quad.area());
System.out.println("The perimeter of the rectangle is: " + Quad.perimeter());
}
}
}
}
Your class that implements the interface does not have methods that matches the interface. The interface's methods return void, while the class returns double. They must match exactly, and probably it is the class that's right and the interface that's wrong -- change the interface method declarations to return double.
In the future, you will want to post all error / exception messages if you have a question about them. It will help us save time and get you better answers.

Where to put Scanner class

As a new student to Java I have bean practicing writing methods and then calling them from a different class. I would like to know how to have the radius determined by user input. I understand I need to use the Scanner class but I'm not sure which class to import the Scanner in and where to put the following bit of code.
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
FIRST FILE - My Methods
package circle;
public class Circle {
private double radius;
final double pi;
public Circle(double radiusIn, double piIn) {
radius = radiusIn;
pi = piIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * pi * radius;
}
public double calculateArea() {
return pi * radius * radius;
}
}
SECOND FILE
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
myCircle = new Circle(3, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Typically you declare variables where you need them in this case that means in the main method where the rest of the user interaction takes place.
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Also Math.PI is a much more accurate approximation of pi. Use that instead of relying on the user to pass in the correct value:
package circle;
public class Circle {
private double radius;
public Circle(double radiusIn) {
radius = radiusIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * Math.PI * radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Think of an Object as an object, like an apple or a toothbrush.
class Circle is a defintion of an Object; it's a description that attempts to match reality. The predefined Java Object is like anything you might find in reality, you can't call eat() on an Object (in the real world) because it might be an apple, but it might be a toothbrush (or a circle).
Therefore, place the code where it makes sense as if it were a real world object. You want to retrieve user input. Does a circle know how to read user input? No!
You call your other class CircleTest. But what it really is, is CircleCreationApplication; that might be a better name for it. In an application that creates circles, you would receive user input. So that is where the code can go. Once you have your user input, you can use that to create the circle.
package circle;
public class CircleCreationApplication {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
userInput.close();
}
}
Note: #ratchetfreak's answer has some other good things. Please read that as well
I think the user interaction code goes into the main class. That's where you handle the workflow, depending on user input. What you actually want is to remove the hardcoded radius (3) and read the value from the user using the Scanner, right?
Then your code snippet goes in the main method, right before instantiating the Circle object.
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
Circle myCircle;
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter ());
System.out.println("Circle circumference is " + myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
You would want to import the scanner and add the code to the second file. Then you can use radius as argument to the Circle constructor instead of just 3.

Categories

Resources