lengths
とwidths
あなたのmainメソッド内の変数ではありませんので、それらを作る:
int lengths = rectangle4.getLengths();
int widths = rectangle4.getWidths();
これらのメソッドは、入力を読んでいるので、あなたは一度だけそれらを呼び出す必要があります。さらに私が覚えていることから、はSystem.in
ストリームを消費するので、一度しか作成しません。
//Simple, short class names are easier to work with
public class Rectangle {
//length and width is data, or "state" of our rectangle, so store it
private final int length;
private final int width;
//Allow creating it without requiring input
public Rectangle(int width, int length) {
this.width = width;
this.length = length;
}
//We create ourselves given a Scanner which we can take input from
public Rectangle(Scanner input) {
System.out.print("Length: ");
this.length = input.nextDouble();
System.out.print("Width: ");
this.width = input.nextDouble();
}
//Calculate based around known information
public double getArea() {
return this.length * this.width;
}
//Calculate based around known information
public double getPerimeter() {
return 2 * (this.length + this.width);
}
//getter
public int getLength() {
return this.length;
}
//getter
public int getWidth() {
return this.width;
}
}
は、このようにそのようにそれの呼び出しを行う:(オブジェクト指向プログラミングのために)今後、私はコンストラクタがScanner
が自分自身を構築するために受け入れ、その後、私は必要な値を返すメソッドを持っているになるだろう:
public static final void main(String... args) {
Scanner input = new Scanner(System.in); //make once
Rectangle rect = new Rectangle(input); //let our rectangle do all the work
//Simple!
System.out.println("Your rectangle has a width of " + rect.getWidth()
+ ", a length of " + rect.getLength()
+ ", the perimeter " + rect.getPerimeter()
+ ", and an area of " + rect.getArea());
}
ここで重要なアイデアれているデータと役割の分離 - Rectangle
情報と自身の創造のすべての側面を管理します。あなたがlength
とを手動で提供するか、またはその情報を入手する手段を提供するかどうか(Scanner
)。 Rectangle
は、必要な情報を保存し、必要な情報(私たちの方法)を返します。これにより、クラスの計算と使用が非常に簡単になります(入力を渡すと、外部の観点から作業が行われます)。
完全なエラーメッセージを含めます。あなたが話していることを理解できるかどうかを確認してください。 – John3136
あなたはあなたの 'main'内のどこにでも' lengths'または 'widths'を宣言していません。これらの変数はそのスコープ内に存在しません。 'double lengths = rectangle4.getLengths();'をメインの上部に向かって配置します。 'widths'に似ています – trooper
@trooperあなたの助けを歓迎します – duckHunter18