Using classes in Java (beginner) - java

I am currently trying to create a class that prints out a rectangle with a height and width 1. I have the program set up (there is a template we are supposed to use) and I incorporated all of the steps. However there is one problem with the return statement on the line "SimpleRectangle(){" it says it is missing a return statement but no matter what I return it still comes up with an error.
public static void main (String[] args){
SimpleRectangle rectangle1=new SimpleRectangle();
System.out.println("The area of radius "+rectangle1.perimeter+" is "+rectangle1.getArea());
}
double height;
double width;
SimpleRectangle(){
height=1;
width=1;
}
double getArea(){
return height*width;
}
double getPerimeter(){
return length+length+width+width;
}
}

This looks like a constructor for a class called SimpleRectange
SimpleRectangle(){
height=1;
width=1;
}
In the code you provide there doesn't seem to be such a class. Make sure your code is included in a class with that name and that it has all the fields you are accessing e.g.
public class SimpleRectangle {
double height;
double width;
double perimeter;
double length;
public static void main(String[] args) {
...
...
}
If your code is in a class with any other name you will get "Invalid method declaration. Return type required"

rectangle1.perimeter is not working because there is no field defined with that name, instead you have a method , therefore you need to call it
this is wrong, you need to do rectangle1.getPerimeter()

rectangle1.perimeter should be rectangle1.getPerimeter()
also you dont have a field called length. it's called height
double getPerimeter(){
return height+height+width+width;
}
the consturctor need to be public
public SimpleRectangle(){
height=1;
width=1;
}

You have several issues with your code it is not compiling
The current error is related to missing class definition, but there will be others.......
Try to not copy and past but to understand what you where missing, class definition, no field declaration for length, wrong call to method ecc.
I have included some public and private declaration I suggest that you study some also what this means...
AND NR 1 TRY TO USE AND IDE AS ECLIPSE, THIS WILL HELP YOU ENORMOUSLY AVOIDING AL OF THESE PROBLEMS AND WHEN YOU LEARN TO DEBUG YOU BECOME A PROGRAMMER., no need for SO, for debugging problems
public class SimpleRectangle {
private double height;
private double width;
public SimpleRectangle() {
this.height = 1;
this.width = 1;
}
public double getArea() {
return height * width;
}
public double getPerimeter() {
return height + height + width + width;
}
public static void main(String[] args) {
SimpleRectangle rectangle1 = new SimpleRectangle();
System.out.println("The area of radius " + rectangle1.getPerimeter() + " is " + rectangle1.getArea());
}
}

In order to use rectangle1.getPerimeter() or rectangle1.getArea(), you need to create a class that looks something like this:
public class SimpleRectangle {
double height;
double width;
SimpleRectangle() {
height = 1;
width = 1;
}
double getArea() {
return height * width;
}
double getPerimeter() {
return 2 * (height + width);
}
}
Then you need to create the object (as shown below) before you can use rectangle1.getPerimeter():
public class MainClass {
public static void main (String[] args) {
SimpleRectangle rectangle1 = new SimpleRectangle();
System.out.println("The area of radius " + rectangle1.getPerimeter() + " is " + rectangle1.getArea());
}
}

Related

About having various constructors and parameters for java

I have written the instructions below and till now, I've came up with having two parameters and letting the method to assign the value and retrieving it. However, one of the instruction I had to follow was to include one constructor with no parameters, so I'm wondering what statement should I make inside the constructor without any parameters. It would be wonderful if anyone gives be a instruction. This is the code I've came up so far.
public class Rectangle {
//first constructor no parameters
//public<class name> (<parameters>)<statements>}
//two parameters one for length, one for width
//member variables store the length and the width
//member methods assign and retrieve the length and width
//returning the area and perimeter
static int recPerimeter(int l, int w) {
return 2*(l+w);
}
static int recArea(int l, int w) {
return l*w;
}
public static void main(String[] args) {
int p = recPerimeter(5, 3);
System.out.println("Perimeter of the rectangle : " + p);
int a = recArea(5,3);
System.out.println("Area of the rectangle : " + a);
}
}
First off, I would take some time to read the java tutorials. At least the "Covering the Basics"
There is a ton wrong with your example. You should store the the attributes of a rectangle - width and length as data members of the class which will get initialized with values through the constructors. If a default constructor is called with no values, then set the attributes to whatever you want. I set them to zero in the example.
Also, you need to normally create an instance of your class and then access it. Big red flag if you are having to prepend "static" to everything.
public class Rectangle {
private int recLength;
private int recWidth;
public Rectangle() {
recLength = 0;
recWidth = 0;
}
public Rectangle( int l, int w ) {
recLength = l;
recWidth = w;
}
public int calcPerimeter() {
return 2*(recLength+recWidth);
}
public int calcArea() {
return recLength*recWidth;
}
public static void main (String [] args) {
Rectangle rec = new Rectangle(5,3);
System.out.println("Perimeter = "+ rec.calcPerimeter());
System.out.println("area = " + rec.calcArea());
}
}

My Java object array only returns the last element

I'm trying to complete a Java lab exercise that asks to display the volumes of objects (cylinders) in an array. Whenever I try to print the array the output always seems to be the last object in the array, when I'd like them all to print.
Here is my code for Cylinder.java:
public class Cylinder implements Comparable<Cylinder> {
public static double radius;
public static double height;
public static String name;
public Cylinder(double radius, double height, String name){
this.radius = radius;
this.height = height;
this.name = name;
}
#Override
public int compareTo(Cylinder obj) {
Cylinder other = obj;
int result;
if (this.volume() > other.volume()){
result = -1;
}
else if (this.volume() < other.volume()){
result = 1;
}
else {
result = 0;
}
return result;
}
public double volume(){
double volume = Math.pow(radius, 2.0)*Math.PI*height;
return volume;
}
public double surface(){
double surface = (4.0*Math.PI)*Math.pow(radius, 2.0);
return surface;
}
public String toString(){
return "Name: " + name + ", radius: " + radius + ", height: " + height ;
}
}
TestSolids.java, to print the array:
import java.util.Arrays;
public class TestSolids {
public static void testCylinderSort(Cylinder[] cylinders){
for(int i = 0; i < cylinders.length; i++){
double volume = cylinders[i].volume();
System.out.println("Volume of Cylinder " + (i+1) + " " + volume);
}
}
public static void main(String[] args){
final Cylinder[] CYLINDERS = { new Cylinder(10, 5, "one"), new Cylinder(5, 10, "two"), new Cylinder(7, 7, "three") };
System.out.println(Arrays.toString(CYLINDERS));
testCylinderSort(CYLINDERS);
}
}
My output:
[Name: three, radius: 7.0, height: 7.0, Name: three, radius: 7.0, height: 7.0, Name: three, radius: 7.0, height: 7.0]
Volume of Cylinder 1 1077.566280181299
Volume of Cylinder 2 1077.566280181299
Volume of Cylinder 3 1077.566280181299
The output shows that I can print the different indexes of the array, but for some reason, they all reference the last element of the array and I can't figure out why that is. If anyone could tell me what's going on here and how I can print all the array objects I'd be very thankful.
You variables declared are static.
You need to remove the static as the static belongs to the class and not a member variable. Thus every time you initialize the values or radius for the cylinders, the following cylinder values always will overwrite the values of the previous ones.
use :
public double radius;
public double height;
public String name;
PS:
You might want to make them private and make public getter and setter methods for better code
Your instance variables are declared as static.
public static double radius;
public static double height;
public static String name;
Static variables are global for that class.
So when you create three objects
final Cylinder[] CYLINDERS = { new Cylinder(10, 5, "one"), new Cylinder(5, 10, "two"), new Cylinder(7, 7, "three") };
The radius, height and name variables are continuously replaced. Consequently the values of these variables are the last values set.
new Cylinder(7, 7, "three")
This is what you perceive as the "iteration always returning the last element".
What's actually happening is that different objects are returned, but they have the same set of variables (at class level), instead of having a set of variables per object (at object level).
The fix is to remove the static keyword.

Passing output from one method to another method java [duplicate]

This question already has answers here:
Passing variable values from another method
(3 answers)
Closed 5 years ago.
I can't seem to grasp this
public static void AreaP(double Dia){
double R = Dia/2.0;
double A = PI * (R * R);
System.out.println("The area is: " + A);
public static void PPSI(double Price){
}
I have to find the price per square inch so I need to pass the area that I solved for in AreaP into the method PPSI and was wondering if there is a way I could do that because I know you can't pass methods into other methods.
public static double A=0;
public static void AreaP(double Dia){
double R = Dia/2.0;
A = PI * (R * R);
System.out.println("The area is: " + A);
System.out.println("The price per square inch is:+PPSI(50))
}
public static double PPSI(double Price){
return Price/A;
}
Making the variable 'A' static and outside the method will allow you to access it from anywhere inside the class or even outside(For.eg, Classname.A )
How about this:
private static final double PI = 3.1416;
public static double areaP(double dia){
double r = dia/2.0;
double a = PI * (r * r);
return a;
}
public static void getPricePerSquareInch(double price){
System.out.print(areaP(75)/price);
}

In Java, can 1 instance variable have 2 potential values?

I have been instructed to "Write a class, Triangle, with one instance variable that takes two string values, (filled or not filled)".
I'm new to Java, and still haven't come across a situation where you could have two potential values for one instance variable.
How would I do this?
main method was given:
public static void main(String[] args)
{
TwoDPolygon polygons[] = new TwoDPolygon[3];
polygons[0] = new Triangle("filled", 8.5, 12.0);
polygons[1] = new Triangle("not Filled", 6.5, 7.5);
polygons[2] = new Triangle(7.0);
for (int i=0; i<polygons.length; i++)
{
System.out.println("Object is " + polygons[i].getName());
System.out.println("Triangle " + polygons[i].getStatus());
System.out.println("Area is " + polygons[i].area());
}
}
Ok I have redesigned the code based on your updated question.
First of all, you need an abstract class called TwoDPolygon. This class is an abstract representation of all your polygons. It contains the constructors and the methods you need.
abstract class TwoDPolygon {
protected String filled;
protected double x;
protected double y;
protected TwoDPolygon(String filled, double x, double y){
this.filled=filled;
this.x=x;
this.y=y;
}
protected TwoDPolygon(double x, double y){
this.x=x;
this.y=y;
}
protected TwoDPolygon(double y){
this.y=y;
}
abstract String getName();
abstract String getStatus();
abstract Double area();
}
Then the next step is to create the Triangle class. You will have to extend the abstract TwoDPolygon. This is the code:
public class Triangle extends TwoDPolygon {
//the first constructor
public Triangle(String filled, double x, double y) {
super(filled, x, y);
}
//the second one
public Triangle(double x, double y){
super(x,y);
}
//the third one
public Triangle(double y){
super(y);
}
public String getName() {
return "Triangle";
}
public String getStatus() {
return filled;
}
public Double area() {
//Insert code here which calculates the area
return 0.0;
}
}
This is all. Every time when you instantiate a Triangle polygon it will chose the right constructor based on the parameters you supply. Now when you run your main you will have the following output:
Object is Triangle
Triangle filled
Area is 0.0
Object is Triangle
Triangle not Filled
Area is 0.0
Object is Triangle
Triangle null
Area is 0.0
Note: The area's code is not done. You will have to do that but I guess that shouldn't be a problem.
Also I have created three constructors as you said, but I don't know the parameters of the third one. I just guessed that it has only the x and y value.
I hope this is what you're looking for!! It shouldn't be that hard to adapt to your specific requirements, as I think it looks almost done.
It is most likely meant that it takes one argument with 2 valid values:
class Triangle {
Triangle(String val) {
if (!"filled".equals(val) || !"not filled".equals(val))
throw ...;
}
}
or enum type
public enum Type {
FILLED,
NOT)FILLED
}
I think what is meant is you have one boolean instance variable named isFilled.
then you could have something like this:
boolean isFilled;
public triangle(String filled, int x, int y) {
if (filled == "filled") {
isFilled = true;
} else if (filled == "notFilled") {
isFilled = false;
} else {
//handle exception or whatever
}
}
That way you can have one instance variable but still use a string in the constructor. I don't think this is a very practical thing to do but if that is what your assignment said then that is a good way to do it. I hope I helped!

Accessing and modifying properties of a super class from sub class?

while trying to get a grasp of polymorphism and inheritance, I made a small program to demonstrate these topics. The program consists of a superclass 'Tree' and three subclasses 'Birch', 'Maple', and 'Oak'. Tree's constructor makes it so that all trees start off with a height of 20 and 200 leaves. In Tree I have an abstract method called grow().
Here's the code for Tree:
public abstract class Tree {
private int height;
private int numberOfLeaves;
public Tree()
{
height = 20;
numberOfLeaves = 200;
}
public Tree(int aheight, int anum)
{
height = aheight;
numberOfLeaves = anum;
}
public int getHeight()
{
return height;
}
public int getNumberOfLeaves()
{
return numberOfLeaves;
}
public void setNumberOfLeaves(int anum)
{
numberOfLeaves = anum;
}
public abstract String getType();
public void setHeight(int aheight)
{
height = aheight;
}
public abstract void grow();
}
Here's the code in Birch for grow().
public void grow()
{
int height = super.getHeight();
super.setHeight(height++);
int num = super.getNumberOfLeaves();
super.setNumberOfLeaves(num+=30);
System.out.println("The Birch is Growing...");
}
However, when I call code to make an array of trees grow, none of their heights or number of leaves change.
Here's the code I used to populate the array of trees (I did it manually):
ArrayList<Tree> treeArray = new ArrayList<Tree>();
treeArray.add( new Oak());
treeArray.add(new Birch());
treeArray.add(new Maple());
And Here's the code I used to call grow:
for (Tree tree : treeArray)
{
tree.grow();
System.out.println("The " + tree.getType() + "'s height is " + tree.getHeight() + " and it's number of leaves is "+ tree.getNumberOfLeaves() +".");
}
Clearly, the values in the superclass aren't being modified. Any help will be appreciated! Thanks!
Change your code to :
int height = super.getHeight();
super.setHeight(++height);
note that you don't need to call super.method(). as long as the method is protected (public even better) you can just simplify it to :
int height = getHeight();
setHeight(++height);
You only call super. if you implement the method again in your child class and want to specifically call the parent class, which usually can be seen in constructor calling parent constructor.
One more thing : your accessor need to be changed a bit just for pre-caution case. see code below. Usually your IDE should support auto generation of accessor.
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
This code:
int height = super.getHeight();
super.setHeight(height++);
isn't going to change anything, because the increment of height will occur after the call to super.setHeight(). So you're just setting the height to its current value.

Categories