方法 - 调用方法

时间:2012-11-23 04:46:44

标签: java methods

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

}

我正在尝试调用方法readInteger来提示用户插入矩形的高度和宽度。这是我第一次使用方法,所以任何帮助都会受到赞赏,我也不确定readInteger方法是否正确。

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用以下语法调用方法:

methodName();

示例:

要调用区域方法,请说:

public static void main(String[] args)
 {
      area(2,3);
 }

注意:在这种情况下隐含对象,因为area方法是public,而static是包含main方法的rectangle类。

如果区域在不同的类中,您将以不同的方式调用方法,首先是实例化,然后是对象的方法调用。

答案 1 :(得分:2)

main()方法中,您可以通过调用readInteger()类中创建的Rectangle方法来读取矩形的长度和宽度:

 int length = readInteger(" For Length ");
 int width = readInteger("For Width ");
 printRectangleDetails(length,width);

首先,将此行添加到readInteger()方法:

  System.out.println (prompt);

答案 2 :(得分:0)

试试这个

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