Method - calling methods - java

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);
}

Related

Printing a rectangle of asterisks in Java

The following is the source code to print a rectangle entirely composed of asterisks (*), with a test class included as well.
import javax.swing.JOptionPane ;
/**
* A class to print block rectangles.
*/
class RectanglePrinter
{
// instance var's
int height ; // height of rectangle (i.e. number of segments)
int width ; // width of each segment(i.e. number of "*"s printed)
/**
* Create a RectanglePrinter object.
* #param height height of rectangle (i.e., number of lines to print)
* #param width width of rectangle (i.e., number of '*'s per line
*/
public RectanglePrinter(int height, int width) // constructor
{
this.height = height ;
this.width = width ;
}
/**
* Prints one line of a rectangle, by printing exactly "width" asterisks
*/
public void printSegment()
{
// write the body of this method here
}
/**
* Prints a rectangle exactly "height" lines in height. Each line is
* printed via a call to method printSegment
*/
public void printRectangle()
{
System.out.println("Printing a " + height + " x " + width + " rectangle:") ;
// write the body of this method here
}
} // end of class rectanglePrinter definition
public class RectanglePrinterTest
{
public static void main (String [] args)
{
String input = JOptionPane.showInputDialog
("What is the height of the rectangle?") ;
int height = Integer.parseInt(input) ;
input = JOptionPane.showInputDialog
("What is the width of the rectangle?") ;
int width = Integer.parseInt(input) ;
RectanglePrinter r = new RectanglePrinter(height, width) ;
System.out.println() ;
r.printRectangle() ;
System.out.println() ;
}
}
In the segments where it says to fill out the method body, I was instructed to use for loops to print out the asterisks. I think I have a basic idea of how to do the printSegment() method:
for (int w = 1; w <= width; w++)
{
System.out.println("*");
}
But from there, I am unsure of what to do within the printRectangle method. Judging from the comments in the code, I think I'm supposed to write a for loop in the printRectangle method that calls the printSegment method, except I don't think you can call a void method within the body of another method. Any help on this would be greatly appreciated.
Update:
I attempted to use the following code within the body of printRectangle()
for (int h = 1; h <= height; h++)
{
printSegment();
}
After running the code and inputting the height and width, I received the following output:
Printing a 6 x 7 rectangle:
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
Now I can print out the asterisks at least, so I just need to know how to modify the code so the output is a rectangular block of asterisks.
Update #2.
I figured out the solution. Here's the code that got me the result I was looking for.
import javax.swing.JOptionPane ;
/**
* A class to print block rectangles.
*/
class RectanglePrinter
{
// instance var's
int height ; // height of rectangle (i.e. number of segments)
int width ; // width of each segment(i.e. number of "*"s printed)
/**
* Create a RectanglePrinter object.
* #param height height of rectangle (i.e., number of lines to print)
* #param width width of rectangle (i.e., number of '*'s per line
*/
public RectanglePrinter(int height, int width) // constructor
{
this.height = height ;
this.width = width ;
}
/**
* Prints one line of a rectangle, by printing exactly "width" asterisks
*/
public void printSegment()
{
// write the body of this method here
for (int w = 1; w <= width; w++)
{
for (int h = 1; h <= height; h++)
{
System.out.print("*");
}
System.out.println();
}
}
/**
* Prints a rectangle exactly "height" lines in height. Each line is
* printed via a call to method printSegment
*/
public void printRectangle()
{
System.out.println("Printing a " + height + " x " + width + " rectangle:") ;
// write the body of this method here
printSegment();
}
} // end of class rectanglePrinter definition
public class RectanglePrinterTest
{
public static void main (String [] args)
{
String input = JOptionPane.showInputDialog
("What is the height of the rectangle?") ;
int height = Integer.parseInt(input) ;
input = JOptionPane.showInputDialog
("What is the width of the rectangle?") ;
int width = Integer.parseInt(input) ;
RectanglePrinter r = new RectanglePrinter(height, width) ;
System.out.println() ;
r.printRectangle() ;
System.out.println() ;
}
}
The differences made: I added a nested for loop in the body of the printSegment() method, and instead of using
System.out.println("*"); , used System.out.print("*") in the innermost loop, and System.out.println() in the outer loop, which resulted in the following output for the input of 5 x 7:
Printing a 5 x 7 rectangle:
*****
*****
*****
*****
*****
*****
*****
It does indeed sound like you are supposed to make a loop in printRectangle where you call printSegment for height amount times.
To call your printSegment method inside printRectangle simply write printSegment(); to call it.
Since its in the same class this is all you have to do to call it. If it were called from another class you can check how RectanglePrinterTest main method calls printRectangle using r.printRectangle(); where r is an instance of the RectanglePrinter class.
As its a void method it wont return anything so you don't need to do anything else. :)
So to sum it up you are on the right track! Keep going and just try what you think feels right and you will surely figure it out.
You need to use the "\n" string to print a new line. It should print the "\n" every time the width or row command is completed.
Using pieces of your code I can now successfully print a rectangle, horizontally.
The Helsinki CS MOOC (http://mooc.cs.helsinki.fi/) presented this task in its learn Java course.
public class MoreStars {
public static void main(String[] args) {
printRectangle(10, 6);
}
public static void printRectangle(int width, int height) {
int i;
int j;
for ( i = 0; i < height; i++ ) {
for ( j = 0; j < width; j++) {
printStars(width);
}
System.out.println("");
}
}
public static void printStars(int amount) {
System.out.print(" * ");
}
}

Multiple Methods in determining Area of Rectangle

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);
}
}

Beginner Java: Variable Scope Issue

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();
}
}

Java Programming Debug Quiz

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.

Why won't my overloaded, static method recognize my height parameter?

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);

Categories