2012-11-23 81 views
1
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方法是否正确。

谢谢!

+0

你提到的所有地方或书籍是什么,这并不能让你理解这一点? –

回答

2

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

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

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

System.out.println (prompt); 
+0

非常感谢,现在就开始工作。现在有道理我实际上看到了正确的代码。 – user1554786

2

你调用一个方法,典型的语法如下:

methodName(); 

例子:

要调用面积法你说:

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

注:对象是在暗示这种情况,因为你的区域方法是公共的,并且对于包含main方法的矩形类是静态的。

如果区域位于不同的类中,您可以通过先实例化然后调用对象的方法来调用该方法。

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