The question that I am really stuck on is this:
Write a program that asks the user to enter the width and length of a rectangle, and then display the rectangle’s area. The program should call the following methods:
• getLength – This method should ask the user to enter the rectangle’s length, and then return that value as a double.
• getWidth – This method should ask the user to enter the rectangle’s width, and then return that value as a double.
• getArea – This method should accept the rectangle’s length and width as arguments, and return the rectangle’s area. The area is calculated by multiplying the length by width.
• displayArea – This method should accept the rectangle’s length, width, and area as arguments, and display them in an appropriate message to the screen.
I don't know how to complete this code because right now what I have is this:
import java.util.Scanner;
public class WidthLengthAreaMethods
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
double length;
double width;
double area;
length = getLength();
width = getWidth();
area = getArea(double length, double width);
displayData(length, width, area);
}
public static double getLength()
{
System.out.println("Enter length. ");
length = keyboard.nextDouble();
System.out.println("The length is " + length);
}
public static double getWidth()
{
double width;
System.out.println("Enter width. ");
width = keyboard.nextDouble();
System.out.println("The width is " + width);
}
public static double getArea()
{
double length;
double width;
double area = length * width;
System.out.println("The area is: " + area);
}
public static void displayData(double length, double width, double area)
{
System.out.println(" The length is: \t" + length);
System.out.println(" The width is: \t" + width);
System.out.println(" The area is: \t" + area);
}
}
What am I screwing up on and how would I go about fixing it? I am a beginner in programming so please bear with me :D.
Thanks guys!!
Since your program is broken up into several methods, the data inside each method is local unless you store it inside the class itself.
For example, your helper functions for getLength() and getWidth() wouldn't be able to access your keyboard Scanner unless you declared it outside of the main method, as such:
import java.util.Scanner;
public class WidthLengthAreaMethods {
Scanner keyboard = new Scanner( System.in );
// Initialized within the class, but outside of any methods
public static void main( String[] args ) {
double length = getLength();
double width = getWidth();
double area = getArea( length, width );
displayData( length, width, area );
}
}
Another alternative would be to pass your Scanner to each of the helper methods in their function calls, e.g.
public static double getLength( Scanner keyboard ){}
While passing the Scanner to each function separately would allow your methods to work as intended, the first option is slightly more readable.
The other thing to consider is that when a method has a return value, such as a double in the case of getLength(), getWidth(), and getArea(), the piece of code calling the function is expecting some variable of that type to be returned. In the case of a void function, such as main() or displayData(), the method states that it will not return a variable of any specific type.
Therefore, when you set length to equal getLength(), what you're trying to do is set the value of your local length variable to equal the value coming back from your helper function. If that value will never be sent, the program will most likely be unable to compile - an error will be thrown stating something along the lines of "expected type double" when you try to call that function. To fix the compiler error, a return statement needs to be added in to the helper functions, such as:
Scanner keyboard = new Scanner( System.in );
public static double getWidth() {
System.out.println("Enter width.");
double width = keyboard.nextDouble(); // Sets the value to return to your main function
System.out.println("The width is " + width);
return width; // Returns the value to your main function
// Causes any code underneath the return statement to be ignored
}
Combining all of that should allow the compiler errors to stop, and make your program work correctly.
Here is the working solution
import java.util.Scanner;
public class WidthLengthAreaMethods {
public static void main(String[]args)
{
double length;
double width;
double area;
length = getLength();
width = getWidth();
area = getArea(length, width);
displayData(length, width, area);
}
public static double getLength()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter length. ");
double length = keyboard.nextDouble();
System.out.println("The length is " + length);
return length;
}
public static double getWidth()
{
Scanner keyboard = new Scanner(System.in);
double width;
System.out.println("Enter width. ");
width = keyboard.nextDouble();
System.out.println("The width is " + width);
return width;
}
public static double getArea(double length, double width)
{
double area = length * width;
System.out.println("The area is: " + area);
return area;
}
public static void displayData(double length, double width, double area)
{
System.out.println(" The length is: \t" + length);
System.out.println(" The width is: \t" + width);
System.out.println(" The area is: \t" + area);
}
}
Related
The following code is what I'm having issues understanding:
public class Rectangle {
public Rectangle() {
double width = 1;
double height = 1;
}
public Rectangle(double w, double h) {
double width = w;
double height = h;
}
public double getArea(double w, double h) {
return (w*h);
}
public double getPerimeter(double w, double h) {
return ((2*w)+(2*h));
}
public static void main(String[] args) {
Rectangle oldRectangle = new Rectangle(4, 40);
Rectangle newRectangle = new Rectangle(3.5, 35.9);
double height1 = oldRectangle.height;
double height2 = newRectangle.height;
double width1 = oldRectangle.width;
double width2 = newRectangle.width;
System.out.println("Width of Rectangle 1 is: " + 4);
System.out.println("Height of Rectangle 1 is: " + 40);
System.out.println("Area of Rectangle 1 is: " + oldRectangle.getArea(4, 40));
System.out.println("Perimeter of Rectangle 1 is: " + oldRectangle.getPerimeter(4, 40));
System.out.println("Width of Rectangle 1 is: " + 3.5);
System.out.println("Height of Rectangle 1 is: " + 35.9);
System.out.println("Area of Rectangle 1 is: " + newRectangle.getArea(3.5, 35.9));
System.out.println("Perimeter of Rectangle 1 is: " + newRectangle.getPerimeter(3.5, 35.9));
}
}
I was instructed to create two constructors for a Rectangle class—one with no arguments but assigned a default value of 1 for both variables width and height. The second constructor was to contain parameters that would take in two doubles that would get assigned to their appropriate variable.
I was then told to create two 'get()' methods that returned their respective values—in my case, they were perimeter and area of said Rectangle.
I was then instructed to create two Rectangle instances, one with a width of 4 and a height of 40—and another with a width of 4.5 and a height of 35.9. So, I did just that and made two new Rectangle objects, as you can see.
Lastly, I was instructed to print out the Width, Height, Perimeter, and Area of both Rectangle objects. My issue is that I don't know of a way to reference them. I took a beginners tutorial class for JavaScript and if I'm not mistaken, I recall there was a way to reference a property value of an object by assigning it to a variable. Again, I'm saying "If I'm not mistaken", so I could be wrong. It's been a while...
I do realize that Java and Java Script are entirely different things in their own right. Java Script was a scripting language developed and based off of Java.
Anyway, any help will be grand.
Please feel free to help me understand how I can implement what I'm trying to do by giving examples. You don't have use my exact code, but I'd like to be able to get my code to make more sense.. I'm using Eclipse btw.
You are on the right track. What you are looking to do is something like this:
public double getArea(Rectangle r){
return r.width*r.height;
}
public double getPerimeter(Rectangle r){
return (2*r.width + 2*r.height);
}
For the print statements you are hard-coding in values which you dont have to do.
System.out.println("Width of Rectangle 1 is: " + oldRectangle.width);
System.out.println("Height of Rectangle 1 is: " + oldRectangle.height);
System.out.println("Area of Rectangle 1 is: " + getArea(oldRectangle));
System.out.println("Perimeter of Rectangle 1 is: " + getPerimeter(oldRectangle));
My issue is that I don't know of a way to reference them
As Java is a strong-typed language, to store the references to each Rectangle (or any object) attribute, you must create variables that match the field.
First, you need your rectangle have attributes:
public class Rectangle {
public double width;
public dobule height;
// constructors here...
After, methods to calculate area and perimeter:
public double getArea() {
return (width*height);
}
public double getPerimeter() {
return ((2*width)+(2*height));
}
Now, to reference them (i guess you still mean area and perimeter):
double area1 = getArea(newRectangle);
double area2 = getArea(oldRectangle);
and
double perimeter1 = getPerimeter(newRectangle);
double perimeter2 = getPerimeter(oldRectangle);
There are no width and height properties in your class, they are only defined inside the constructor, declare them in the class and not inside the constructors so you can acces them like this:
public class Rectangle {
double width;
double height;
public Rectangle() {
width = 1;
height = 1;
}
public Rectangle(double w, double h) {
width = w;
height = h;
}
public double getArea(double w, double h) {
return (w*h);
}
public double getPerimeter(double w, double h) {
return ((2*w)+(2*h));
}
//....
}
Note: It's better to declare them as private and use getters and setters to acces them, take a look at Adding Setter and Getter Methods for further information.
EDIT:
In your case you don't need to pass parameters to your methods (because the calculation needs this rectangle width and height), just calculate them using your class fields, like this:
public double getArea() {
return (width*height);
}
public double getPerimeter() {
return ((2*width)+(2*height));
}
Here's what you need to do to acces your variables:
public static void main(String[] args) {
Rectangle oldRectangle = new Rectangle(4, 40);
Rectangle newRectangle = new Rectangle(3.5, 35.9);
//In the following you access all the object variables and methods
System.out.println("Width of Rectangle 1 is: " + oldRectangle.width);
System.out.println("Height of Rectangle 1 is: " + oldRectangle.height);
System.out.println("Area of Rectangle 1 is: " + oldRectangle.getArea());
System.out.println("Perimeter of Rectangle 1 is: " + oldRectangle.getPerimeter());
System.out.println("Width of Rectangle 1 is: " + newRectangle.width);
System.out.println("Height of Rectangle 1 is: " + newRectangle.height);
System.out.println("Area of Rectangle 1 is: " + newRectangle.getArea());
System.out.println("Perimeter of Rectangle 1 is: " + newRectangle.getPerimeter());
}
You can test the DEMO here.
And to answer your question about using constructor, calling the parametrized constructor like this:
Rectangle oldRectangle = new Rectangle(4, 40);
Is equivalent to:
// create the object
Rectangle oldRectangle = new Rectangle();
//And then assigning the values 4 and 40 to its width and height
oldRectangle.width=4;
oldRectangle.height=40;
I'm practicing some work from my java book and I'm having an issue with getting a method to use a variable for a calculation. Please note that this is a work in progress and I'm only trying to get it to use the circleArea method to calculate the area of a circle at the moment. Here is the necessary code:
public class Geometry
{
public static void printMenu()
{
System.out.println("This is a geometry calculator\nChoose what you would like to calculate" + "\n1. Find the area of a circle\n2. Find the area of a rectangle\n3."
+ " Find the area of a triangle\n4. Find the circumference of a circle."
+ "\n5. Find the perimeter of a rectangle\n6. Find the perimeter of a triangle"
+ "\nEnter the number of your choice:");
}
public static void circleArea(double area)
{
System.out.println(Math.PI*Math.pow(radius, 2));
}
public static void main(String[] args)
{
int choice; //the user's choice
double value = 0; //the value returned from the method
char letter; //the Y or N from the user's decision to exit
double radius; //the radius of the circle
double length; //the length of the rectangle
double width; //the width of the rectangle
double height; //the height of the triangle
double base; //the base of the triangle
double side1; //the first side of the triangle
double side2; //the second side of the triangle
double side3; //the third side of the triangle
}
}
Please declare a variable of class and call the function from it.
public class Geometry
{
int choice; //the user's choice
double value = 0; //the value returned from the method
char letter; //the Y or N from the user's decision to exit
double radius; //the radius of the circle
double length; //the length of the rectangle
double width; //the width of the rectangle
double height; //the height of the triangle
double base; //the base of the triangle
double side1; //the first side of the triangle
double side2; //the second side of the triangle
double side3; //the third side of the triangle
public static void printMenu()
{
System.out.println("This is a geometry calculator\nChoose what you would like to calculate"
+ "\n1. Find the area of a circle\n2. Find the area of a rectangle\n3."
+ " Find the area of a triangle\n4. Find the circumference of a circle."
+ "\n5. Find the perimeter of a rectangle\n6. Find the perimeter of a triangle"
+ "\nEnter the number of your choice:");
}
public static void circleArea(double area)
{
System.out.println(Math.PI*Math.pow(radius, 2));
}
public static void main(String[] args)
{
Geometry g = new Geometry();
g.printMenu();
}
}
This quiz is in two parts. First is
public class FixDebugBox {
private int width;
private int length;
private int height;
private double Volume;
public void FixDebugbox() {
length = 1;
width = 1;
height = 1;
}
public FixDebugBox(int width, int length, int height) {
width = width;
length = length;
height = height;
}
public void showData() {
System.out.println("Width: " + width + " Length: " +
length + " Height: " + height);
}
public double getVolume() {
double vol = length * width * height;
return Volume;
}
}
The code above is one half of the quiz, it have the code above complied correctly but the second part I can't
public class FixDebugFour3
// This class uses a FixDebugBox class to instantiate two Box objects
{
public static void main(String args[])
{
int width = 12;
int length = 10;
int height = 8;
FixDebugBox box1 = new FixDebugBox(width, length, height);
FixDebugBox box2 = new FixDebugBox(width, length, height);
System.out.println("The dimensions of the first box are");
box1.showData();
System.out.println("The volume of the first box is");
showVolume(box1);
System.out.println("The dimensions of the first box are");
box2.showData();
System.out.println("The volume of the second box is");
showVolume(box2);
}
public void showVolume() {
double vol = FixDebugBox.getVolume();
System.out.println(vol);
}
}
I keep getting an error with double vol = FixDebugBox.getVolume(); error: non-static method getVolume() cannot be referenced from a static context
FixDebugBox.getVolume();
getVolume is non static method you can not call this with class name, its a public method which you need object to call it.
public void showVolume(FixDebugBox box) {
double vol = box.getVolume();
System.out.println(vol);
}
Now give me the prize. :D
I think you already answered yourself. You need to hold a reference to an instance of FixDebugBox in order to call its non-static methods.
As the error message says, you can't call a non-static method from the static context that is the main method. While you could turn your showVolume() to be a static method and take a FixDebugBox instance as an argument, seeing how FixDebugBox objects already have a getVolume() method, just call it for each instance:
System.out.println(box1.getVolume());
...
System.out.println(box2.getVolume());
Also, don't change the name of your Volume variable to volume. You should use camelCase.
If you move
public void showVolume() {
double vol = FixDebugBox.getVolume();
System.out.println(vol);
}
to the class FixDebugBox
and remove the getVolume() method inclass FixDebugBox , and change the showVolume() method to:
public void showVolume() {
double vol = length * width * height;
Volume = vol;
System.out.println(Volume);
}
That would fix your program. Also boxVolume would be a better name instead of Volume, since variables are not supposed to be written with a capital letter.
So I have three static, overloaded methods that are used in my AreaClient class that are taking input from the user and passing what those inputs are as parameters to the methods below. For some reason though I can't seem to get the last area method to take in my hieght variable as a parameter. I keep getting an error saying "cannot find symbol". These are supposed to be overloaded methods, just what the assignment says. Sorry if this is real simple but I am pretty new to programming. Here is the code that I wrote.
import java.util.Scanner; // Needed for the Scanner class
public class AreaClient {
public static void main(String[] args) {
double circleRadius; //input for radius of circle
int width, length; //input for rectangle width and length
double cylinderRadius, height; //input for radius of a cylinder and hieght
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// gathering input for radius of circle
System.out.println("Enter radius of circle");
circleRadius = keyboard.nextDouble();
// input for width and length of rectangle
System.out.println("Enter width of rectangle");
width = keyboard.nextInt();
System.out.println("Enter length of rectangle");
length = keyboard.nextInt();
// input for radius and hieght of cylinder
System.out.println("Enter radius of cylinder");
cylinderRadius = keyboard.nextDouble();
System.out.println("Enter hieght of cylinder");
height = keyboard.nextDouble();
//returning area methods results and storing them in new variables
double circleArea = area(circleRadius);
int rectangleArea = area(width, length);
double cylinderArea = area(cylinderRadius, height);
//displaying results of methods
System.out.println("The area of your circle is: " + circleArea);
System.out.println("The area of your rectangle is: " + rectangleArea);
System.out.println("The area of your cylinger is: " + cylinderArea);
}
//overloaded methods that take different inputs
public static double area(double r)
{
return 3.14159265359 * Math.pow(r, 2);
}
public static int area(int w, int l)
{
return w * l;
}
//actual method that doesn't recognize h inside
public static double area(double r, double h)
{
return 2*3.14159265359 * Math.pow(r,2) + h (2*3.14159265359*r);
}
}
And the error msg I am getting
AreaClient.java:54: error: cannot find symbol
return 2*3.14159265359 * Math.pow(r,2) + h (2*3.14159265359*r);
^
symbol: method h(double)
location: class AreaClient
1 error
Thanks guys. Any help is much appreciated.
Notice in the error message:
symbol: method h(double)
Why it is looking for a method called h() which accepts a double? Because you're telling it to:
h (2*3.14159265359*r)
h isn't a method, it's just a value. You need to use an operator to connect it to that other value. I think you meant to do this:
h * (2*3.14159265359*r)
I think you mean: h * (2*3.14159265359*r). Without the operator, Java thinks you're trying to call a method named h(double)
return 2*3.14159265359 * Math.pow(r,2) + h * (2*3.14159265359*r);
import java.util.Scanner;
public class Rectangle
{
public static void main(String[] args)
{
-Don't know how to call method here-
}
/**
* returns the area of a rectangle
* #param height the height of the rectangle
* #param width the width of the rectangle
*/
public static int area (int length, int width)
{
return length * width;
}
/**
* returns the perimeter of a rectangle
* #param height the height of the rectangle
* #param width the width of the rectangle
*/
public static int perimeter (int length, int width)
{
return length + width;
}
/**
* returns the details of the rectangle
* #param height the height of the rectangle
* #param width the width of the rectangle
*/
public static void printRectangleDetails (int length, int width)
{
System.out.println ("This is the length of the rectangle " + length);
System.out.println ("This is the width of the rectangle " + width);
System.out.println (("This is the perimeter of the rectangle " + (length + width)));
System.out.println (("This is the area of the rectangle " + (length * width)));
}
/**
* Read in an integer and return its value
* #param the prompt to be shown to the user
*/
public static int readInteger(String prompt)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
int input = scan.nextInt();
return input;
}
}
I'm trying to call the method readInteger to prompt the user to insert the rectangle's height and width. This is my first experience with methods so any help would be appreciated, I'm also not sure if the readInteger method is correct.
Thanks!
In your main() method, you can read the length and width of the rectangle by calling the readInteger() method that you have created in the Rectangle class as:
int length = readInteger(" For Length ");
int width = readInteger("For Width ");
printRectangleDetails(length,width);
First of all, add this line to readInteger() method:
System.out.println (prompt);
You call a method, typical with the following syntax:
methodName();
Example:
To call the area method you say:
public static void main(String[] args)
{
area(2,3);
}
Note: the object is implied in this case since your area method is public and static to the rectangle class which contains the main method.
If area was in a different class you would make the call the method differently, by instantiation first and then a method call on the object.
Try this
public static void main(String[] args) {
Scanner s= new Scanner(System.in) ;
System.out.print("Enter length : " );
int len=Integer.parseInt( s.nextLine()) ;
System.out.print("\nEnter width : ");
int wd=Integer.parseInt( s.nextLine()) ;
printRectangleDetails(len,wd);
}