2

2 つのインスタンス変数 (幅と高さ) と 2 つのインスタンス メソッド (面積と円周) を持つJava クラスを作成しましたRectangle。両方のメソッドはパラメーターを取りませんが、double 値を返します。area メソッドは長方形の面積 (幅 * 高さ) を返し、円周は (2*幅 + 2*高さ) を返します。次に、main メソッドを使用して Demo クラスを作成し、4 つのオブジェクトをインスタンス化してクラス Rectangle をテストし、ユーザーに各インスタンスの幅と高さを入力するように求めます。次に、各インスタンスの面積と円周を出力します。

2 つのクラスを作成し、最初のクラスは Rectangle です。

public class Rectagle {

    private double width;
    private double height;

    public double area() {
        return width * height;
    }

    public double circumference() {
        return 2*width+2*height;
    }
}

そして、クラスをテストするための 2 番目のクラス Demo を作成します。

import java.util.Scanner;
public class Demo {
    public static void main(String []args){
        Scanner console=new Scanner(System.in);
    Rectagle R1=new Rectagle();
    Rectagle R2=new Rectagle();
    Rectagle R3=new Rectagle();
    Rectagle R4=new Rectagle();

    }
}

私の問題、この点がわかりません」というメッセージが表示され、ユーザーは各インスタンスの幅と高さを入力するように求められます。次に、各インスタンスの面積と円周を出力します。

4

3 に答える 3

1

コンストラクターにはパラメーターがありません。幅と高さに値を割り当てる方法はありません。

この種のコンストラクターを使用することをお勧めします

public Rectangle(double w, double h){
     width = w;
     height = h;
}

次のように使用します。

 Rectagle R1=new Rectagle(30.0, 40.0);

または、必要に応じて、次のようにインスタンス変数にセッターとゲッターを追加します。

public void setWidth(double w){
   width = w
}

public double getWidth(){
   return width;
}

これでクラスは完了です。Scannerコンソールから読み取る方法を知るには、クラスの適切な使用を参照してください。たとえば、これを読んでください:Javaで標準入力から整数値を読み取る方法

于 2012-12-22T08:13:30.607 に答える
1

これが役に立ちますように

public class Rectangle {

    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getArea() {
        return width * height;
    }

    public double getCircumference() {
        return 2*width+2*height;
    }

    @Override
    public String toString() {
        return "Rectangle["+width+","+height+"]Area:"+getArea()+",Circumference:"+getCircumference();
    }

    public static void main(String[] args) {
         Scanner console=new Scanner(System.in);
        double width = getValue(console, "Width");
        double height = getValue(console, "Height");
        Rectangle rectangle = new Rectangle(width, height);
        System.out.println(rectangle);

    }

    public static double getValue(Scanner console, String name) {
        System.out.println("Enter "+name + " : ");
        String widthStr = console.nextLine();
        double parseDouble;
        try {
            parseDouble = Double.parseDouble(widthStr);
        }catch(NumberFormatException ne) {
            System.out.println("Unable to parse your input, enter correct value ");
            return getValue(console, name);
        }
        return parseDouble;
    }
}
于 2012-12-22T08:34:34.660 に答える