首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >方法调用方法

方法调用方法
EN

Stack Overflow用户
提问于 2012-11-23 12:46:44
回答 3查看 201关注 0票数 1
代码语言:javascript
复制
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方法是否正确。

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-23 13:09:10

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

代码语言:javascript
复制
 int length = readInteger(" For Length ");
 int width = readInteger("For Width ");
 printRectangleDetails(length,width);

首先,将这一行添加到readInteger()方法中:

代码语言:javascript
复制
  System.out.println (prompt);
票数 2
EN

Stack Overflow用户

发布于 2012-11-23 12:48:26

通常使用以下语法调用方法:

代码语言:javascript
复制
methodName();

示例:

要调用面积方法,您可以这样说:

代码语言:javascript
复制
public static void main(String[] args)
 {
      area(2,3);
 }

注意:这个对象在本例中是隐含的,因为你的area方法对于包含main方法的rectangle类来说是公共的和静态的。

如果area在不同的类中,您可以通过不同的方式调用方法,首先实例化,然后在对象上调用方法。

票数 2
EN

Stack Overflow用户

发布于 2012-11-23 13:07:49

尝尝这个

代码语言:javascript
复制
 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);     
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13523241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档