Problem Statement is "To develop a Java Program to create an abstract class named Shape that contains two integers and an empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method printArea() that prints the area of the given shape."
In this program, I want to get the two integer values contained by the abstract class Shape, from the user (run time) instead of compile time.
This is my code
abstract class Shape
{
abstract void Printarea();
int a=10,b=2;;
}
class Rectangle extends Shape
{
void Printarea()
{
System.out.println("area of rectangle is "+(a*b));
}
}
class Triangle extends Shape
{
void Printarea()
{
System.out.println("area of triangle is "+(0.5*a*b));
}
}
class Circle extends Shape
{
void Printarea()
{
System.out.println("area of circle is "+(3.14*a*a));
}
}
class Main
{
public static void main(String []args)
{
Shape=b;
b=new Circle();
b.Printarea();
b=new Rectangle();
b.Printarea();
b=new Triangle();
b.Printarea();
}
}
Add Setter and getter method for variables a,b ;
here's my code
package com.docker.container.controllers;
/**
* #author atwa Jul 29, 2018
*/
public abstract class Shape {
abstract void Printarea();
int a = 10, b = 2;
/**
* #return the a
*/
public int getA() {
return a;
}
/**
* #param a
* the a to set
*/
public void setA(int a) {
this.a = a;
}
/**
* #return the b
*/
public int getB() {
return b;
}
/**
* #param b
* the b to set
*/
public void setB(int b) {
this.b = b;
}
static public class Rectangle extends Shape {
void Printarea()
{
System.out.println("area of rectangle is " + (a * b));
}
}
static class Triangle extends Shape
{
void Printarea()
{
System.out.println("area of triangle is " + (0.5 * a * b));
}
}
static class Circle extends Shape
{
void Printarea()
{
System.out.println("area of circle is " + (3.14 * a * a));
}
}
// area of circle is 314.0
// area of rectangle is 20
// area of triangle is 10.0
public static void main(String[] args)
{
Shape b = new Circle();
b.setA(5);
b.setB(5);
b.Printarea();
b = new Rectangle();
b.Printarea();
b = new Triangle();
b.Printarea();
}
}
you can use Scanner class
like this
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
}
Some quick code but works as expected and would give you idea:
import java.util.Scanner;
abstract class Shape {
int a = 10, b = 2;
Shape(int a, int b){
this.a=a;
this.b=b;
}
abstract void Printarea();
}
class Rectangle extends Shape {
Rectangle(int a, int b) {
super(a, b);
}
void Printarea() {
System.out.println("area of rectangle is " + (a * b));
}
}
class Triangle extends Shape {
Triangle(int a, int b) {
super(a, b);
}
void Printarea(){
System.out.println("area of triangle is " + (0.5 * a * b));
}
}
class Circle extends Shape {
Circle(int a, int b) {
super(a, b);
}
void Printarea() {
System.out.println("area of circle is " + (3.14 * a * a));
}
}
class Z {
public static void main(String[] args){
Shape shape=null;
String input;
int width, height;
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("which shape? circle/rectangle/triangle (write any other thing for quitting): ");
input = scanner.nextLine();
if(!"circle".equalsIgnoreCase(input) && !"rectangle".equalsIgnoreCase(input) && !"triangle".equalsIgnoreCase(input) ){
System.exit(0);
}
System.out.println("height: ");
height = scanner.nextInt();
System.out.println("width: ");
width = scanner.nextInt();
if("circle".equalsIgnoreCase(input)){
shape=new Circle(width, height);
}
else if("rectangle".equalsIgnoreCase(input)){
shape=new Rectangle(width, height);
}
else{ // == triangle
shape=new Triangle(width, height);
}
shape.Printarea();
}
}
}
Try with this:
public class Main {
public static void main(String[] args) {
Shape b;
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
b = new Circle(x, y);
b.Printarea();
b = new Rectangle(x, y);
b.Printarea();
b = new Triangle(x, y);
b.Printarea();
}
private static int Abs(int a) {
return a < 0 ? -a : a;
}
}
abstract class Shape {
int a, b;
public Shape(int a, int b) {
this.a = a;
this.b = b;
}
abstract void Printarea();
}
class Rectangle extends Shape {
public Rectangle(int a, int b) {
super(a, b);
}
void Printarea()
{
System.out.println("area of rectangle is " + (a * b));
}
}
class Triangle extends Shape {
public Triangle(int a, int b) {
super(a, b);
}
void Printarea()
{
System.out.println("area of triangle is " + (0.5 * a * b));
}
}
Related
I have some class Shape.
public abstract class Shape {
String shapeColor;
public Shape(String shapeColor){
this.shapeColor = shapeColor;
}
abstract public double calcArea();
#Override
public String toString() { return "Shape"; }
public String getShapeColor() { return shapeColor; }
}
Also, I have classes that extend from Shape: Triangle, Rectangle and Circle.
public class Triangle extends Shape {
double a, h;
public Triangle(String shapeColor, double a, double h) {
super(shapeColor);
this.a = a;
this.h = h;
}
#Override
public double calcArea() {return a * h / 2;}
#Override
public String toString() {
return "Triangle";
}
}
public class Rectangle extends Shape {
double a, b;
public Rectangle(String shapeColor, double a, double b) {
super(shapeColor);
this.a = a;
this.b = b;
}
#Override
public double calcArea() {
return a * b;
}
#Override
public String toString() {
return "Rectangle";
}
}
public class Circle extends Shape {
double r;
public Circle(String shapeColor, double r) {
super(shapeColor);
this.r = r;
}
#Override
public double calcArea() {
return (Math.PI * r * r);
}
#Override
public String toString() {
return "Circle";
}
}
I want to create Arraylist<Shape> shapes and add shapes to it based on user input.
So, I want to have something like
String[] userInput = scanner.nextLine().split(", ");
Shape shape = createNewShape(userinput)
For example:
"Circle, Blue, 7" -> Shape shape = new Circle("Blue", 7)
"Rectangle, Red, 5, 10" -> Shape shape = new Rectangle("Red", 5, 10)
But I want this to work even if new class that extends from Shape is created.
For example if I will have new Shape Cube I will not have need to add something to my code:
"Cube, Red, 9" -> Shape shape = new Cube("Red", 9)
This question is close to what I need, but my classes have different amount of parameters. Maybe someone can give me a piece of advice how to make it work for different amount of parameters.
You can search for Constructors on a specific package.
For example, put all your shapes together in a x-named package and call Class.forName to get them.
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>();
shapes.add(create("Triangle", "Orange", 5, 6));
shapes.add(create("Circle", "Blue", 7));
shapes.add(create("Rectangle", "Red", 5, 10));
shapes.forEach(System.out::println);
}
private static Shape create(String constructor, Object... objects) {
try {
final Constructor<?> _constructor = Class.forName("com.shapes." + constructor).getConstructors()[0];
return (Shape) _constructor.newInstance(objects);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
My structure:
+com.mainPackage
main.java
+com.shapes
Shape.java
Triangle.java
Rectangle.java
Circle.java
I have an interface that has one ordinary method and one generic method. I have implemented ordinary method for two different classes, but do not now how to do that with generic method. Here is my code:
Sphere.java:
public class Sphere implements GeometricShape<Sphere> {
private double radius;
public Sphere (double radius) {
this.radius = radius;
}
public double volume() {
return (4.0 / 3.0) * Math.PI * radius * radius * radius;
}
public void describe() {
System.out.println("Sphere[radius=" + radius + "]");
}
#Override
public Sphere supersize()
{
this.radius*=2;
return new Sphere(radius);
}
}
Rectangle.java
public class Rectangle implements TwoDShape {
private double width, height;
public Rectangle (double width, double height) {
this.width = width;
this.height = height;
}
public double area()
{
return width * height;
}
public double perimeter()
{
return 2.0 * (width + height);
}
public void describe()
{
System.out.println("Rectangle[width=" + width + ", height=" + height + "]");
}
#Override
public Rectangle supersize()
{
this.width*=2;
this.height*=2;
return new Rectangle(width, height);
}
}
TwoDShape.java:
public interface TwoDShape extends GeometricShape
{
public double area();
}
ThreeDShape.java:
public interface ThreeDShape extends GeometricShape<ThreeDShape>
{
public double volume();
}
GeometricShape.java:
public interface GeometricShape<T extends GeometricShape<T>>
{
public void describe();
public T supersize();
}
and finally main class ArrayListExample.java:
import java.util.ArrayList;
public class ArrayListExample {
public static void describe_all( ArrayList<? extends GeometricShape> shapes )
{
for(int i=0;i<shapes.size();i++)
{
shapes.get(i).describe();
}
System.out.println("Total number of shapes:"+ shapes.size());
}
public static void main(String[] args) {
System.out.println("The describe() method:");
System.out.println();
System.out.println("Example rectangles");
ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
rects.add(new Rectangle(2.0, 3.0));
rects.add(new Rectangle(5.0, 5.0));
describe_all(rects);
System.out.println();
ArrayList<Sphere> spheres = new ArrayList<Sphere>();
spheres.add(new Sphere(10.0));
spheres.add(new Sphere(50.0));
spheres.add(new Sphere(0.0));
System.out.println("Example spheres");
describe_all(spheres);
System.out.println();
System.out.println("The supersize() method:");
System.out.println();
ArrayList<Rectangle> double_rects = supersize_list(rects);
describe_all(double_rects);
System.out.println();
ArrayList<Sphere> double_spheres = supersize_list(spheres);
describe_all(double_spheres);
}
}
How can I implement supersize_list method that it takes supersize method from both rectangle and sphere and outputs like
Rectangle[width=4.0, height=6.0]
Rectangle[width=10.0, height=10.0]
Total number of shapes: 2
Sphere[radius=20.0]
Sphere[radius=100.0]
Sphere[radius=0.0]
Total number of shapes: 3
Could you help me with this, please? I greatly appreciate your help!
The class hierarchy looks inconsistent. For example, you have ThreeDShape extends GeometricShape<ThreeDShape> and TwoDShape extends GeometricShape at the same time, for no obvious reason. It's not fun to write a generic method for these types.
Here's a less-confusing version. (I hope) Note: I choose not to change the size of the shape itself in supersize method, instead let it return a bigger shape while keeping the original unchanged.
1. GeometricShape
/**
* A geometric shape interface. You can do two things with it.
* 1. Ask it to describe itself (to stdout);
* 2. Ask it to return a bigger version of itself (double the size).
*/
public interface GeometricShape<T extends GeometricShape<T>> {
/**
* Print a description to STDOUT
*/
void describe();
/**
* Returns a bigger shape.
* #return Something that's a GeometricShape
*/
T supersize();
}
2. Shape2D and Rectangle
/**
* A 2-dimensional shape.
* It has area.
* Its supersize() method should return a Shape2D instance.
*/
public interface Shape2D<T extends Shape2D<T>> extends GeometricShape<T> {
double area();
}
/**
* A rectangle.
*/
public final class Rectangle implements Shape2D<Rectangle> {
private final double width;
private final double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
#Override
public String toString() {
return "Rectangle{" +
"width=" + width +
", height=" + height +
'}';
}
#Override
public void describe() {
System.out.println(this);
}
#Override
public Rectangle supersize() {
return new Rectangle(width*2, height*2);
}
#Override
public double area() {
return width * height;
}
}
3. Shape3D and Sphere
/**
* A 3-dimensional shape.
* It has volume.
* Its supersize() method should return a Shape3D instance.
*/
public interface Shape3D<T extends Shape3D<T>> extends GeometricShape<T> {
double volume();
}
/**
* A sphere
*/
public final class Sphere implements Shape3D<Sphere> {
private final double radius;
public Sphere(double radius) {
this.radius = radius;
}
#Override
public String toString() {
return "Sphere{" +
"radius=" + radius +
'}';
}
#Override
public void describe() {
System.out.println(this);
}
#Override
public Sphere supersize() {
return new Sphere(radius*2);
}
#Override
public double volume() {
return 4*Math.PI*Math.pow(radius, 3)/3;
}
}
Now the generic method that transforms a list
public static <T extends GeometricShape<T>>
List<T> supersize_list(List<T> list) {
List<T> result = new ArrayList<>();
for (T shape : list) {
result.add(shape.supersize());
}
return result;
}
You do not need to return a new Object. For Rectangle for example
#Override
public void supersize()
{
this.width*=2;
this.height*=2;
}
is sufficient
So, i kinda wrote this Code for the game called "towers of hanoi".
The code i had before was showing the moves for every step in the console. I am trying to show the moves graphically.
I think i came pretty far, but i cant implement the paint Method.
I tried several things like g.drawRect(s1.x,s1.y+200,s1.width,s1.height); but its just showing an rectangle, no moves etc.
Heres my Code:
import java.io.*;
import java.util.*;
import java.awt.*;
public class hanoi {
public static void ziehe_scheibe(MyFrame f,Pole von, Pole nach) {
int hs = von.onPole.size();
int ht = nach.onPole.size();
int hy = -25*(ht-hs+1);
int hx = (nach.xPos - von.xPos);
String d = von.scheibenehmen();
nach.scheibelegen(d);
f.moveDisk(d,hx,hy);
}
public static void hanoi(MyFrame f,int n, Pole platz1, Pole platz2, Pole hilfsplatz) {
if ( n==1 )
ziehe_scheibe(f,platz1,platz2);
else
{ hanoi(f,n-1,platz1,hilfsplatz,platz2);
ziehe_scheibe(f,platz1,platz2);
hanoi(f,n-1,hilfsplatz,platz2,platz1);
}
}
public static int xSize(String d) {
if ( d == "klein" ) return 30;
if ( d == "mittel" ) return 40;
else return 50;
}
public static void main(String args[]) {
Pole p1 = new Pole("a",60);
Pole p2 = new Pole("b",180);
Pole p3 = new Pole("c",300);
p1.scheibelegen("groß");
p1.scheibelegen("mittel");
p1.scheibelegen("klein");
Rectangle r1 = new Rectangle(p1.xPos-50,50,100,20);
Rectangle r2 = new Rectangle(p1.xPos-40,25,80,20);
Rectangle r3 = new Rectangle(p1.xPos-30,0,60,20);
MyFrame fff = new MyFrame(r1,r2,r3);
fff.setSize(800,600);
fff.setVisible(true);
hanoi(fff,3,p1,p3,p2);
}
}
// Frame-Klasse zur Anzeige des Zustandes
class MyFrame extends Frame {
public Rectangle s1, s2, s3;
public MyFrame(Rectangle a, Rectangle b, Rectangle c) {
s1 = a; s2 = b; s3 = c;
}
public void paint(Graphics g) {
}
public Rectangle xRect(String d) {
if ( d == "klein" ) return s3;
if ( d == "mittel" ) return s2;
else return s1;
}
public void moveDisk(String name,int dx,int dy)
{ xRect(name).translate(dx,dy);
repaint();
try
{ System.in.read();System.in.read(); }
catch (Exception e) {}
}
}
// Pole-Klasse: Repräsentation eines Stabes
class Pole {
public String label;
public Vector onPole;
public int xPos;
public Pole(String s, int i) {
onPole=new Vector();
label = s; xPos = i;
}
public void scheibelegen(String d) {
this.onPole.addElement(d);
}
public String scheibenehmen() {
Object lastEl = this.onPole.lastElement();
String lastElStr = lastEl.toString();
this.onPole.removeElement(lastEl);
return lastElStr;
}
}
Maybe you guys can take a look on it
btw excuse my bad english
Try
public static int xSize(String d) {
if ( d.equals("klein")) return 30;
if ( d.equals("mittel")) return 40;
else return 50;
}
//With these I am getting compilation - error class not found
/*import Shape.TwoD.*;
import Shape.ThreeD.*;
import Shape.*;*/
import Shape.TwoD.Circle;
import Shape.TwoD.Line;
import Shape.ThreeD.Line3D;
import Shape.ThreeD.Sphere;
import Shape.Actions;
public class Test {
/**
* Creates a new instance of <code>Test</code>.
*/
int o;
public Test() {
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Actions obj[] = new Actions[4];
obj[0] = new Line(1,2,3,4);
obj[1] = new Circle(1,2,3);
obj[2] = new Line3D(1,2,3,4,5,6);
obj[3] = new Sphere(1,2,3,4);
for(Actions x: obj)
x.draw();
Actions.TwoD o =(Circle)obj[1];
System.out.println("Area of circle "+o.area());
o = (Sphere)obj[3];
System.out.println("Volume of sphere "+o.area());
}
}
Action is an interface which contains nested interface TwoD and ThreeD
Why import with wildcard not working in the above code? Am I using it wrong?
I couldn't find any related answer, if both wildcard and fully qualified imports are not working then there is problem in my code but in this case, compilation error occur class not found only when I use wildcard with import.
EDIT:
Sorry for the wrong naming convention, Line,Circle,Line3D and Sphere are the classes
Lineand Circle comes under Shape.TwoD
Line3D and Sphere comes under Shape.ThreeD
Actions.java:
package Shape;
public interface Actions {
interface ThreeD{
double volume();
}
interface TwoD{
double area();
}
void draw();
//void erase();
final double pi = 3.142857;
}
Line.java:
package Shape.TwoD;
public class Line implements Shape.Actions{
BaseObj.Point p1,p2;
public Line(int x1,int y1, int x2 ,int y2) {
p1 = new BaseObj.Point(x1,y1);
p2 = new BaseObj.Point(x2,y2);
}
public void draw(){
//System.out.println("Line between ("+p1.x+","+p1.y+") and ("+p2.x+","+p2.y+"));
System.out.println("Line between ("+p1.getx()+","+p1.gety()+") and ("+p2.getx()+","+p2.gety()+") has been drawn");
}
}
Circle.java:
package Shape.TwoD;
public class Circle extends BaseObj.Point implements Shape.Actions, Shape.Actions.TwoD{
protected int radius;
public Circle(int x, int y, int radius) {
super(x,y);
this.radius = radius;
}
public void draw(){
System.out.println("Circle with ("+x+","+y+") as center and radius "+radius+" units has been drawn");
}
public double area(){
return (pi*radius*radius);
}
}
Line3D.java:
package Shape.ThreeD;
public class Line3D implements Shape.Actions {
BaseObj.Point3D p1,p2;
public Line3D(int x1,int y1, int z1, int x2,int y2, int z2) {
p1 = new BaseObj.Point3D(x1,y1,z1);
p2 = new BaseObj.Point3D(x2,y2,z2);
}
public void draw(){
//System.out.println("Line between ("+p1.x+","+p1.y+") and ("+p2.x+","+p2.y+"));
System.out.println("Line between ("+p1.getx()+","+p1.gety()+","+p1.getz()+") and ("+p2.getx()+","+p2.gety()+","+p2.getz()+") has been drawn");
}
}
Sphere.java:
package Shape.ThreeD;
public class Sphere extends Shape.TwoD.Circle{
int z;
public Sphere(int x, int y, int z, int radius) {
super(x,y,radius);
this.z = z;
}
public void draw(){
System.out.println("Spere with ("+x+","+y+","+z+") as center and radius "+radius+" units has been drawn");
}
public double volume(){
return(radius*radius*pi*4/3);
}
public double area(){
System.out.println("Sphere is a 3D object so 2D quantitys doesnt apply");
return 0.0;
}
}
Edit2:
After correcting the names I got error that Actions interface is duplicate so I changed its name into ObjActions and the problem resolved. Thanks for the help. I hope the naming convention I used below is consistent with standard.
ObjActions.java
package shape;
public interface ObjActions {
interface Actions3D{
double volume();
}
interface Actions2D{
double area();
}
void draw();
//void erase();
final double pi = 3.142857;
}
Circle.java
package shape.twod;
public class Circle extends baseobj.Point implements shape.ObjActions, shape.ObjActions.Actions2D{
protected int radius;
public Circle(int x, int y, int radius) {
super(x,y);
this.radius = radius;
}
public void draw(){
System.out.println("Circle with ("+x+","+y+") as center and radius "+radius+" units has been drawn");
}
public double area(){
return (pi*radius*radius);
}
}
Line.java
package shape.twod;
public class Line implements shape.ObjActions{
baseobj.Point p1,p2;
public Line(int x1,int y1, int x2 ,int y2) {
p1 = new baseobj.Point(x1,y1);
p2 = new baseobj.Point(x2,y2);
}
public void draw(){
//System.out.println("Line between ("+p1.x+","+p1.y+") and ("+p2.x+","+p2.y+"));
System.out.println("Line between ("+p1.getx()+","+p1.gety()+") and ("+p2.getx()+","+p2.gety()+") has been drawn");
}
}
Line3D.java
package shape.threed;
public class Line3D implements shape.ObjActions {
baseobj.Point3D p1,p2;
public Line3D(int x1,int y1, int z1, int x2,int y2, int z2) {
p1 = new baseobj.Point3D(x1,y1,z1);
p2 = new baseobj.Point3D(x2,y2,z2);
}
public void draw(){
//System.out.println("Line between ("+p1.x+","+p1.y+") and ("+p2.x+","+p2.y+"));
System.out.println("Line between ("+p1.getx()+","+p1.gety()+","+p1.getz()+") and ("+p2.getx()+","+p2.gety()+","+p2.getz()+") has been drawn");
}
}
Sphere.java
package shape.threed;
public class Sphere extends shape.twod.Circle implements shape.ObjActions.Actions3D{
int z;
public Sphere(int x, int y, int z, int radius) {
super(x,y,radius);
this.z = z;
}
public void draw(){
System.out.println("Spere with ("+x+","+y+","+z+") as center and radius "+radius+" units has been drawn");
}
public double volume(){
return(radius*radius*pi*4/3);
}
}
Test.java
package test;
import shape.twod.*;
import shape.threed.*;
import shape.*;
/*import shape.twod.Circle;
import shape.twod.Line;
import shape.threed.Line3D;
import shape.threed.Sphere;
import shape.Actions;*/
public class Test {
/**
* Creates a new instance of <code>Test</code>.
*/
int o;
public Test() {
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ObjActions obj[] = new ObjActions[4];
obj[0] = new Line(1,2,3,4);
obj[1] = new Circle(1,2,3);
obj[2] = new Line3D(1,2,3,4,5,6);
obj[3] = new Sphere(1,2,3,4);
for(ObjActions x: obj)
x.draw();
ObjActions.Actions2D o =(Circle)obj[1];
//Actions2D o =(Circle)obj[1];
System.out.println("Area of circle "+o.area());
ObjActions.Actions3D op = (Sphere)obj[3];
System.out.println("Volume of sphere "+op.volume());
}
}
The "packages" TwoD and ThreeD might get shadowed by the interfaces Action.TwoD and Action.ThreeD (or vice versa) as per JLS 7.5.2:
The declaration might be shadowed by a single-type-import declaration of a type whose simple name is Vector; by a type named Vector and declared in the package to which the compilation unit belongs; or any nested classes or interfaces.
The declaration might be obscured by a declaration of a field, parameter, or local variable named Vector.
(It would be unusual for any of these conditions to occur.)
I am a new programmer and i am getting the error cannot find symbol in my ShapeApp class.
My error is
System.out.println("Current length of rectangle is: " + r1.getLength());
^
symbol: variable r1
location: class ShapeApp
Please try and explain it in a simpler way. Thank you very much and my codes are below.
public class Rectangle
{
protected double length;
protected double width;
public Rectangle() { }
public Rectangle(double l,double w)
{
length = l;
width = w;
}
public void setLength(double l) {length = l;}
public double getLength() {return length;}
public void setWidth(double w) {width = w;}
public double getWidth() {return width;}
public double findArea() {return length * width;}
public String toString()
{
return "\tLength " + length + "\tWidth " + width;
}
}
public class Box extends Rectangle
{
private double height;
public Box() { }
public Box(double l,double w,double h)
{
super(l,w);
height = h;
}
public void setHeight(double h) {height = h;}
public double getHeight() {return height;}
public double findArea() {return ((super.findArea() * 2) + (2 * height * width) + (2 * height * length));}
public double findVolume() {return super.findArea() * height;}
public String toString()
{
return super.toString() + "\tHeight " + height;
}
}
import java.util.*;
public class ShapeApp
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(20,10);
Box b1 = new Box(10,5,5);
int options;
Scanner input = new Scanner(System.in);
do{
displayMenu();
options = input.nextInt();
switch(options)
{
case 1: changeRecL();
break;
case 2: changeBoxL();
break;
case 3: changeBoxH();
break;
case 4: displayAreaRec();
break;
case 5: displaySaBox();
break;
case 6: displayVoBox();
break;
case 0: System.out.println("Exiting Program");
break;
default: System.out.println("Invalid Option. ");
}
}while(options != 0);
}
public static void displayMenu()
{
System.out.println("-------------------------------MENU-------------------------------");
System.out.println("[1] Change the length of rectangle");
System.out.println("[2] Change the length of box");
System.out.println("[3] Change the height of box");
System.out.println("[4] Display the area of rectangle");
System.out.println("[5] Display the surface area of box");
System.out.println("[6] Display the volume of box");
System.out.println("[0] Exit");
System.out.println("------------------------------------------------------------------");
System.out.println("Enter your option:");
}
public static void changeRecL()
{
Scanner input = new Scanner(System.in);
System.out.println("Current length of rectangle is: " + r1.getLength());
System.out.println("Enter new length of rectangle: ");
double nlength = input.nextDouble();
r1.setLength(nlength);
}
public static void changeBoxL()
{
}
public static void changeBoxH()
{
}
public static void displayAreaRec()
{
}
public static void displaySaBox()
{
}
public static void displayVoBox()
{
}
}
That's because you havent defined r1 in your method changeRecL.
Perhaps you wanted to pass that r1 from main to your method like below:
case 1: changeRecL(r1);
And accept R1 as below in the same:
public static void changeRecL(Rectangle r1)
When you define an object class you can make several instances of the class as objects. There's not only one Rectangle r1. If you want to use only one rectangle for everything you should implement a Singleton class.
public class Rectangle {
double len;
double wid;
private static Rectangle instance = null;
protected Rectangle() {
// Exists only to defeat instantiation.
}
public static Rectangle getInstance() {
if(instance == null) {
instance = new Rectangle();
}
return instance;
}
public static void setLen (double l){
len = l;
}
public static double getLen (){
return len;
}
public static void setWid (double w){
wid = w;
}
public static double getWid(){
return wid;
}
}
But, like #almas_shaikh said, it's easier to pass the object instance to the method.
Also, let me remind you that the word length is used by java to determine size of arrays and other objects, as getLength() method. You should use another name to length attribute and method to avoid conflicts.