Question

In: Computer Science

I have the following code for my java class assignment but i am having an issue...

I have the following code for my java class assignment but i am having an issue with this error i keep getting.

On the following lines:

return new Circle(color, radius);

return new Rectangle(color, length, width);

I am getting the following error for each line:

"non-static variable this cannot be referenced from a static context"

Here is the code I have:

/*
* ShapeDemo - simple inheritance hierarchy and dynamic binding.
*
* The Shape class must be compiled before the derived classes
* Circle, Rectangle, and Square can be compiled.
*
* The Shape, Circle, Rectangle, and Square classes
* must be compiled before this democlass can be compiled.
*
*/

import java.util.Scanner;

public class ShapeDemo
{
  
/**
* getShape - read a Shape's description and create the specific object
*/
public static Shape getShape()
{
Scanner sc = new Scanner(System.in);

// Continue asking for input until a valid shape entered, or 'done'
do {
System.out.println("\nEnter the shape's color (or 'done')...");
String color = sc.nextLine();
if (color.equalsIgnoreCase("done")) {
return null;
}
if (!color.equalsIgnoreCase("red") &&
!color.equalsIgnoreCase("blue") &&
!color.equalsIgnoreCase("green")) {
System.out.println(" Error - color must be 'red', 'blue', or 'green'");
continue;
}

System.out.println("Enter shape type...");
String name = sc.nextLine();
if (name.equalsIgnoreCase("circle")) {
System.out.println("Enter the radius...");
double radius = sc.nextDouble();
if (radius < 0.0) {
System.out.println("Radius must be non-negative");
continue;
}
return new Circle(color, radius);
} else if (name.equalsIgnoreCase("rectangle")) {
System.out.println("Enter the length and width...");
double length = sc.nextDouble();
double width = sc.nextDouble();
if (length < 0.0 || width < 0.0) {
System.out.println("length and width must be non-negative");
continue;
}
return new Rectangle(color, length, width);
} else if (name.equalsIgnoreCase("square")) {
System.out.println("Enter the length of a side...");
double length = sc.nextDouble();
if (length < 0.0) {
System.out.println("length must be non-negative");
continue;
}
return new Square(color, length);
} else {
System.out.println("shape name must be 'circle', 'rectangle', or 'square'");
continue;
}
} while (true);

}

/**
* main
*/
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);

// Create an array of Shape references larger than the maximum number
// of Shapes to be read (could also prompt for size).
Shape[] slist = new Shape[50];

// Read shapes until null returned. Note that this code doesn't know what
// specific type of Shape has been returned.
System.out.println("Enter a list of shapes - 'done' to end");
Shape sp;
int numShapes = 0;
while (null != (sp = getShape())) {
slist[numShapes++] = sp;
}

// Print the list of shapes. Get the specific Shape's information using
// dynamic binding to call the implementation of toString() defined for
// the actual type of Shape referenced.
System.out.println("\nThe list of shapes entered...");
for (int n = 0; n < numShapes; ++n) {
System.out.println(" " + slist[n].toString());
}

// Sort the list of shapes into ascending order by area. Get the each
// specific shape's area using dynamic binding to call the implementation
// of area() defined for the the actual type of Shape referenced.
System.out.println("\nSorting shapes into order by area...");


// TODO - call the sortArray method to sort the array of Shapes.
// Pass slist and numShapes as parameters.
sortArray(slist,numShapes);
// Print the sorted list of shapes.
System.out.println("\nThe sorted list of shapes...");
for (int n = 0; n < numShapes; ++n) {
System.out.println(" " + slist[n].toString());
}

// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
String junk = sc.nextLine();
}

// TODO - add the sortArray method to sort the array of Shapes into
// ascending order. The array and number of shapes in it must be passed
// as parameters.
public static void sortArray(Shape[] slist, int numShapes)
{
int i,j;
Shape temp;
for(i=0; i<numShapes-1; i++)
for(j=i+1; j<numShapes; j++)
if(slist[i].area()>slist[j].area()){
temp=slist[i];
slist[i]=slist[j];
slist[j]=temp;
}
}
  
public class Shape
{
private String color;
public Shape(String color)
{
this.color=color;
}
public String getColor()
{
return color;
}
public double area()
{
return 0.0;
}
public String toString()
{
return "generic shape";
}
}
  
public class Circle extends Shape
{
private double radius;
public Circle(String color, double radius)
{
super(color);
this.radius=radius;
}
public double area()
{
return (Math.PI*Math.pow(this.radius, 2));
}
public double getRadius()
{
return radius;
}
public String toString()
{
return getColor()+" Circle with radius of "+radius+" and area of "+area();
}
}
  
public class Square extends Shape
{
private double length;
public Square(String color, double length)
{
super(color);
this.length=length;
}
public double area()
{
return length*length;
}
public double getLength()
{
return length;
}
public String toString()
{
return getColor()+" Square with side length of "+length+" and area of "+area();
}
}
  
public class Rectangle extends Square
{
private double width;
public Rectangle(String color, double length, double width)
{
super(color, length);
this.width=width;
}
public double area()
{
return getLength()*width;
}
public double getWidth()
{
return width;
}
public String toString()
{
return getColor()+" Rectangle with length of "+getLength()+" and width of "+width+" and area of "+area();
}
}
  
}

Solutions

Expert Solution

Shape.java :

public class Shape {
   private String color;

   public Shape(String color) {
       this.color = color;
   }

   public String getColor() {
       return color;
   }

   public double area() {
       return 0.0;
   }

   public String toString() {
       return "generic shape";
   }
}

********************************************

Circle.java :

public class Circle extends Shape {
   private double radius;

   public Circle(String color, double radius) {
       super(color);
       this.radius = radius;
   }

   public double area() {
       return (Math.PI * Math.pow(this.radius, 2));
   }

   public double getRadius() {
       return radius;
   }

   public String toString() {
       return getColor() + " Circle with radius of " + radius + " and area of " + area();
   }
}

****************************************

Rectangle.java :

public class Rectangle extends Square {
   private double width;

   public Rectangle(String color, double length, double width) {
       super(color, length);
       this.width = width;
   }

   public double area() {
       return getLength() * width;
   }

   public double getWidth() {
       return width;
   }

   public String toString() {
       return getColor() + " Rectangle with length of " + getLength() + " and width of " + width + " and area of "
               + area();
   }
}
******************************************

Square.java :

public class Square extends Shape {
   private double length;

   public Square(String color, double length) {
       super(color);
       this.length = length;
   }

   public double area() {
       return length * length;
   }

   public double getLength() {
       return length;
   }

   public String toString() {
       return getColor() + " Square with side length of " + length + " and area of " + area();
   }
}

*******************************************************

ShapeDemo.java :

/*
* ShapeDemo - simple inheritance hierarchy and dynamic binding.
*
* The Shape class must be compiled before the derived classes
* Circle, Rectangle, and Square can be compiled.
*
* The Shape, Circle, Rectangle, and Square classes
* must be compiled before this democlass can be compiled.
*
*/
//import package
import java.util.Scanner;
//Java class
public class ShapeDemo {

   /**
   * getShape - read a Shape's description and create the specific object
   */
   public Shape getShape() {
       Scanner sc = new Scanner(System.in);

// Continue asking for input until a valid shape entered, or 'done'
       do {
           System.out.println("\nEnter the shape's color (or 'done')...");
           String color = sc.nextLine();
           if (color.equalsIgnoreCase("done")) {
               return null;
           }
           if (!color.equalsIgnoreCase("red") && !color.equalsIgnoreCase("blue") && !color.equalsIgnoreCase("green")) {
               System.out.println(" Error - color must be 'red', 'blue', or 'green'");
               continue;
           }

           System.out.println("Enter shape type...");
           String name = sc.nextLine();
           if (name.equalsIgnoreCase("circle")) {
               System.out.println("Enter the radius...");
               double radius = sc.nextDouble();
               if (radius < 0.0) {
                   System.out.println("Radius must be non-negative");
                   continue;
               }
               return new Circle(color, radius);
           } else if (name.equalsIgnoreCase("rectangle")) {
               System.out.println("Enter the length and width...");
               double length = sc.nextDouble();
               double width = sc.nextDouble();
               if (length < 0.0 || width < 0.0) {
                   System.out.println("length and width must be non-negative");
                   continue;
               }
               return new Rectangle(color, length, width);
           } else if (name.equalsIgnoreCase("square")) {
               System.out.println("Enter the length of a side...");
               double length = sc.nextDouble();
               if (length < 0.0) {
                   System.out.println("length must be non-negative");
                   continue;
               }
               return new Square(color, length);
           } else {
               System.out.println("shape name must be 'circle', 'rectangle', or 'square'");
               continue;
           }
       } while (true);

   }

   /**
   * main
   */
   public static void main(String[] args) {
       // Object of ShapeDemo
       ShapeDemo d = new ShapeDemo();
       Scanner sc = new Scanner(System.in);

// Create an array of Shape references larger than the maximum number
// of Shapes to be read (could also prompt for size).
       Shape[] slist = new Shape[50];

// Read shapes until null returned. Note that this code doesn't know what
// specific type of Shape has been returned.
       System.out.println("Enter a list of shapes - 'done' to end");
       Shape sp;
       int numShapes = 0;
       while (null != (sp = d.getShape())) {
           slist[numShapes++] = sp;
       }

// Print the list of shapes. Get the specific Shape's information using
// dynamic binding to call the implementation of toString() defined for
// the actual type of Shape referenced.
       System.out.println("\nThe list of shapes entered...");
       for (int n = 0; n < numShapes; ++n) {
           System.out.println(" " + slist[n].toString());
       }

// Sort the list of shapes into ascending order by area. Get the each
// specific shape's area using dynamic binding to call the implementation
// of area() defined for the the actual type of Shape referenced.
       System.out.println("\nSorting shapes into order by area...");

// TODO - call the sortArray method to sort the array of Shapes.
// Pass slist and numShapes as parameters.
       sortArray(slist, numShapes);
// Print the sorted list of shapes.
       System.out.println("\nThe sorted list of shapes...");
       for (int n = 0; n < numShapes; ++n) {
           System.out.println(" " + slist[n].toString());
       }

// Keep console window alive until 'enter' pressed (if needed).
       System.out.println();
       System.out.println("Done - press enter key to end program");
       String junk = sc.nextLine();
   }

// TODO - add the sortArray method to sort the array of Shapes into
// ascending order. The array and number of shapes in it must be passed
// as parameters.
   public static void sortArray(Shape[] slist, int numShapes) {
       int i, j;
       Shape temp;
       for (i = 0; i < numShapes - 1; i++)
           for (j = i + 1; j < numShapes; j++)
               if (slist[i].area() > slist[j].area()) {
                   temp = slist[i];
                   slist[i] = slist[j];
                   slist[j] = temp;
               }
   }
}
=========================================

Output :


Related Solutions

I am having an issue with the code. The issue I am having removing the part...
I am having an issue with the code. The issue I am having removing the part when it asks the tuter if he would like to do teach more. I want the program to stop when the tuter reaches 40 hours. I believe the issue I am having is coming from the driver. Source Code: Person .java File: public abstract class Person { private String name; /** * Constructor * @param name */ public Person(String name) { super(); this.name =...
I am having trouble with my assignment and getting compile errors on the following code. The...
I am having trouble with my assignment and getting compile errors on the following code. The instructions are in the initial comments. /* Chapter 5, Exercise 2 -Write a class "Plumbers" that handles emergency plumbing calls. -The company handles natural floods and burst pipes. -If the customer selects a flood, the program must prompt the user to determine the amount of damage for pricing. -Flood charging is based on the numbers of damaged rooms. 1 room costs $300.00, 2 rooms...
I am struggling with this assignment for my java class. Objectives: Your program will be graded...
I am struggling with this assignment for my java class. Objectives: Your program will be graded according to the rubric below. Please review each objective before submitting your work so you don’t lose points. 1.Create a new project and class in Eclipse and add the main method. (5 points) 2. Construct a Scanner to read input from the keyboard. (5 points) 3. Prompt the user with three questions from the Psychology Today quiz, and use the Scanner to read their...
I have the following assignment for probability class: I am supposed to write a routine (code)...
I have the following assignment for probability class: I am supposed to write a routine (code) in MATLAB that does solve the following problem for me: a) Generate N=10000 samples of a Uniform random variable (X) using the rand () command. This Uniform RV should have a range of -1 to +3. b) Generate (Estimate) and plot the PDF of X from the samples. You are not allowed to use the Histogram () command, any commands from the Matlab Statistics...
I'm getting an error with my code on my EvenDemo class. I am supposed to have...
I'm getting an error with my code on my EvenDemo class. I am supposed to have two classes, Event and Event Demo. Below is my code.  What is a better way for me to write this? //******************************************************** // Event Class code //******************************************************** package java1; import java.util.Scanner; public class Event {    public final static double lowerPricePerGuest = 32.00;    public final static double higherPricePerGuest = 35.00;    public final static int cutOffValue = 50;    public boolean largeEvent;    private String...
Hello i am working on an assignment for my programming course in JAVA. The following is...
Hello i am working on an assignment for my programming course in JAVA. The following is the assignment: In main, first ask the user for their name, and read the name into a String variable. Then, using their name, ask for a temperature in farenheit, and read that value in. Calculate and print the equivalent celsius, with output something like Bob, your 32 degrees farenheit would be 0 degrees celsius Look up the celsius to farenheit conversion if you do...
Hello, I am having difficulty with this assignment. I chose Amazon as my stock, but I...
Hello, I am having difficulty with this assignment. I chose Amazon as my stock, but I am confused on what they're asking :             Choose a stock that interests you. Utilizing Bloomberg (or other financial websites) as a source of data, collect the following      information:                         a. The stock’s Beta                         b. The rate of return on the market (S&P 500 Index)                         c. The risk-free rate (rRF)                         d. The last dividend paid (D0)...
I am having an issue with the Java program with a tic tac toe. it isn't...
I am having an issue with the Java program with a tic tac toe. it isn't a game. user puts in the array and it prints out this. 1. Write a method print that will take a two dimensional character array as input, and print the content of the array. This two dimensional character array represents a Tic Tac Toe game. 2. Write a main method that creates several arrays and calls the print method. Below is an example of...
hello, I am having an issue with a question in my highway engineering course. the question...
hello, I am having an issue with a question in my highway engineering course. the question is: An equal tangent sag vertical curve has an initial grade of –2.5%. It is known that the final grade is positive and that the low point is at elevation 82 m and station 1 + 410.000. The PVT of the curve is at elevation 83.5 m and the design speed of the curve is 60 km/h. Determine the station and elevation of the...
Hi, Working on a project in my group for class and I am having some issues...
Hi, Working on a project in my group for class and I am having some issues My part is current state of the business. It is a store and the annual sales are $460,000 Other info I have is: Ownership and Compensation; Percent Ownership Personal Investment Mitchell George, Founder & CEO 25% $125,000Katie Beauseigneur, COO 15% $75,000 Melissa Dunnells, CFO15% $75,000 Also, a medium coffee price from store is $3.75 Sarah Griffin, Marketing Officer 10% $50,000 Katharina Ferry, HR Director10%...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT