Why will this not return the area? - java

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.

Related

Store objects in ArrayList and output Object description

I am writing a program with separate files in the same package. What I want to do is to use in my Main.java file :
1-Use the values entered by the user create three Triangle objects and stores them in an ArrayList.
2-Display the string representation of each Triangle object in the ArrayList, by calling its toString( ) method and its getArea() method. See the output example below.
I want all the ouput to display after all the inputs. What I mean is that I want the description of each triangle object to be displayed at the end
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("*******************************************************************");
System.out.println("* This program gets input for three triangles from the user. *\n" + "* It then creates three Triangle objects and displays the *\n" + "* description of each.. *");
System.out.println("*******************************************************************");
System.out.println(); // for adding blank line
Scanner input = new Scanner(System. in );
Triangle triangle; //Define the triangle object
ArrayList < GeometricObject > list = new java.util.ArrayList < >();;
for (int i = 1; i < 2; i++) {
System.out.print("Enter the color of a triangle" + i + "(e.g. \"red\"): ");
String color = input.next();
System.out.print("Is the triangle filled (y or n): ");
boolean filled;
String filledString = input.next();
filled = filledString.equals("y"); // condition returns true if "y" is entered
// User input for triangle's 3 sides
System.out.println("Enter the lengths of the three sides of the triangle: ");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
// we need to create the triangle object with the input
triangle = new Triangle(side1, side2, side3);
triangle.setColor(color); // calls setColor from GeometricObject
triangle.setFull(filled); // calls setFilled as well
// Display the triangle, very similar to TestCircleRectangle.java example
System.out.println(); // for adding blank line
System.out.println("Triangle: side1 = " + side1 + "," + " side2 = " + side2 + "," + " side3 = " + side3);
System.out.println(triangle.toString());
System.out.printf("Area = %.2f\n", triangle.getArea());
System.out.println(); // for adding blank line
}
System.out.println("Goodbye...");
}
}
Triangle.java
public class Triangle extends GeometricObject {
// Contains 3 double data fields value to 0
private double side1;
private double side2;
private double side3;
/** Default constructor that creates a triangle
* with default side of 1.0 each
* */
Triangle() {
side1 = 1.0;
side2 = 1.0;
side3 = 1.0;
}
/** parameterized constructor that creates
* a triangle with sides values
* */
Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
/** Getter for side1 */
public double getSide1() {
return side1;
}
/** Setter for side1 */
public void setSide1(double newSide1) {
side1 = newSide1;
}
/** Getter for side2 */
public double getSide2() {
return side2;
}
/** Setter for side2 */
public void setSide2(double newSide2) {
side2 = newSide2;
}
/** Getter for side3 */
public double getSide3() {
return side3;
}
/** Setter for side3 */
public void setSide3(double newSide3) {
side3 = newSide3;
}
/**
* The getArea Method
* Purpose: Computes the area of a triangle from 3 sides
* #return the area of a triangle
*/
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
}
GeometricObject.java
public class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/** Construct a default geometric object */
public GeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with the specified color
* and filled value */
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
this.dateCreated = new java.util.Date();
}
/** Return color */
public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
this.color = color;
}
/** Return filled. Since filled is boolean,
its getter method is named isFilled
*/
public boolean Full() {
return filled;
}
/** Set a new filled */
public void setFull(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}
/**
* Abstract method getArea
*/
/** Return a string representation of this object */
public String toString() {
return "created on " + getDateCreated() + "\ncolor: " + color + " and filled: " + filled;
}
}
(This should probably be more of a comment than an answer, but I am not sufficiently well known in these parts to comment. I am working on that!).
As NotZack said, you haven't actually told us what the problem is. For example, showing us the program's current output compared to what you are aiming for (literally, write down what you want the program to print) would help us know where to start looking.
However, I did notice a few things from quickly looking through your code:
you declare an ArrayList in the main file, but I don't see it being used anywhere. What was the intention of this item?
take a deep, deep look at the following line from main:
for (int i = 1; i < 2; i++)
Get yourself a pen and piece of paper, and write down each value of i in turn which this loop will deal with, bearing in mind the starting value and strictly less than condition. Is this what you want it to do?
Hopefully that gives you something to start working with :)
First you need to add the triangle object to list. And move all the code related to printing triangle move outside the for loop.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<GeometricObject> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
System.out.print("Enter the color of a triangle" + i + "(e.g. \"red\"): ");
String color = scan.next();
System.out.print("Is the triangle filled (y or n): ");
boolean filled = scan.next().equalsIgnoreCase("y");
System.out.println("Enter the lengths of the three sides of the triangle: ");
double side1 = scan.nextDouble();
double side2 = scan.nextDouble();
double side3 = scan.nextDouble();
Triangle triangle = new Triangle(side1, side2, side3);
list.add(triangle);
}
list.forEach(System.out::println);
//Equivalent for above line
/*for(GeometricObject shape: list){
System.out.println(shape);
}*/
}
And also add the toString() method in Triangle class
You don't need to call the toString() method explicitly when you try to print the object it will automatically call the toString() method.
#Override
public String toString() {
return "Triangle: " +
"side1=" + side1 +
", side2=" + side2 +
", side3=" + side3 +
", Area=" + getArea() +
"\n" + super.toString();
}

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

Java function returning zero as a result

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

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

When I try to invoke method "calcArea", error message "non-static method calcArea() cannot be referenced from a static context" appears

I've messed around with this for an hour now and can't get it to work. I've also looked this question up but the wording used in answers I've found haven't helped me at all.
Any help would be much appreciated.
Also, the invocation in question is at the very end of the program, inside main.
import java.util.Scanner;
public class Area {
Scanner input = new Scanner (System.in);
/**
* #param args the command line arguments
*/
public static void areaTriangle (double height, double length){
System.out.println((height * length) * .5);
}
public static void areaRectangle (double height, double length,
double width){
System.out.println(height * length * width);
}
public static void areaCircle (double radius){
System.out.println(Math.PI * (radius * radius));
}
public void calcArea (){
double i;
System.out.println("Which shape's area would you like to calculate?: \n"
+ "Enter '1' for Triangle \n"
+ "Enter '2' for Rectangle \n"
+ "Enter '3' for Circle \n"
+ "Enter '0' to quit the program");
i = input.nextDouble();
if (i == 1)
{
System.out.print("Enter the height of your triangle: ");
double height = input.nextDouble();
System.out.print("Enter the height of your length: ");
double length = input.nextDouble();
areaTriangle(height, length);
}
else if ( i == 2)
{
System.out.print("Enter the height of your rectangle: ");
double height = input.nextDouble();
System.out.print("Enter the length of your rectangle: ");
double length = input.nextDouble();
System.out.print("Enter the width of your rectangle: ");
double width = input.nextDouble();
areaRectangle(height, length, width);
}
else if ( i == 3)
{
System.out.print("Enter the radius of your circle");
double radius = input.nextDouble();
areaCircle(radius);
}
else if ( i == 0)
return;
else
System.out.println("Please input a number from 0 - 3");
}
public static void main(String[] args) {
calcArea();
}
}
put static in calcArea
public static void calcArea ()
or you can do this in your main
public static void main(String[] args) {
YourClassName variable= new YourClassName();
variable.calcArea();
}
just change the "YourClassName" to the name of your class and also you can change the variable object

Categories