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メソッドが正しいかどうかもわかりません。

ありがとう!

4

3 に答える 3

2

次の構文で一般的なメソッドを呼び出します。

methodName();

例:

エリアメソッドを呼び出すには、次のようにします。

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

注:この場合、areaメソッドはパブリックであり、mainメソッドを含むrectangleクラスに対して静的であるため、オブジェクトは暗黙的に示されます。

エリアが別のクラスにある場合は、最初にインスタンス化してからオブジェクトに対してメソッドを呼び出すことにより、メソッドを別の方法で呼び出します。

于 2012-11-23T04:48:26.100 に答える
2

メソッドでは、クラスで作成しmain()たメソッドを次のように呼び出すことで、長方形の長さと幅を読み取ることができます。readInteger()Rectangle

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

まず、次の行を readInteger() メソッドに追加します。

  System.out.println (prompt);
于 2012-11-23T05:09:10.407 に答える
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);     
 }
于 2012-11-23T05:07:48.707 に答える