Need Help - Basic Java

Posts 1–6 of 6 · Page 1 of 1
Need Help - Basic Java
Can anyone tell me how to get area for the Rectangle?

I know I did something wrong with this code:

Code:
import java.awt.Rectangle;


public class AreaTester
{
	
		public static void main(String[] args)
		{
		
		Rectangle r1 = new Rectangle (10, 20, 30, 50);
		r1.getWidth();
		r1.getHeight();
		double r1.area = width*height;
		
		System.out.println("Area = " + area);
		
		}
}
That code...

Have you tried to get a book and learn?

Code:
public static void main(String[] args)
{
	Rectangle r1 = new Rectangle (10, 20, 30, 50);
	double area = r1.getWidth() * r1.getHeight();

	System.out.println("Area = " + area);
}
Thanks, but I was looking for another way

BTW, I do have a book and I AM learning.
Quote Originally Posted by redspartan927 View Post
Thanks, but I was looking for another way

BTW, I do have a book and I AM learning.
which way?
Code:
		double r1.area = width*height;
		
		System.out.println("Area = " + area);
is where your problem lies.
you dont need to re-declare r1.area as a double, as i assume it is a public field in the Rectangle class already. Now on the second line, you attempted to print a local variable named area which does not exist. You need to print r1.area, as area is stored in that object of the Rectangle class, not your local class.
Quote Originally Posted by Saltine View Post
Code:
		double r1.area = width*height;
		
		System.out.println("Area = " + area);
is where your problem lies.
you dont need to re-declare r1.area as a double, as i assume it is a public field in the Rectangle class already. Now on the second line, you attempted to print a local variable named area which does not exist. You need to print r1.area, as area is stored in that object of the Rectangle class, not your local class.
it doesn't matter, Rectangle r1 and dobule r1 are two different variables, Java can differ an object and a double even if they use the same name.
his problem is that getWidth() and getLength() are not voids, but doubles (assuming they are doubles and not integers, else he would've {int area}), therefore he must have done
Code:
public static void main(String[] args)
		{
		
		Rectangle r1 = new Rectangle (10, 20, 30, 50);
		double width= r1.getWidth();
		double height= r1.getHeight();
		double area = width*height;
		
		System.out.println("Area = " + area);
		
		}
sticking to his way of writing this, of course it's best to keep it with less variables.
Posts 1–6 of 6 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us