私はオブジェクトを学習しており、それを知るにはさまざまなことを試みています。私は2つの方法のうち1つを返すintを書いたし、私が望むように動作します。しかし、他の1つは、私は奇妙な数字を与える間違って何かをやっているTufferのBCです。 Box calculateArea2を書くにはどうすればいいですか?(私はゲッターとセッターを見ましたが、まだそれらのことは学んでいませんでした)。ここに私のコードです。どのように領域の計算のrefrence変数を返すメソッドを印刷できますか?
public static void main(String[] args) {
Box box1 = new Box();
Box box2 = new Box();
String str = JOptionPane.showInputDialog("Enter a length and width");
Scanner input = new Scanner(str);
box1.length = input.nextInt();
box1.width = input.nextInt();
int BoxsArea = calculateArea(box1); // calculate box1
JOptionPane.showMessageDialog(null, " First Box's area is: "+BoxsArea);
String str2 = JOptionPane.showInputDialog("Enter a length and width");
input = new Scanner(str2);
box2.length = input.nextInt();
box2.width = input.nextInt();
Box box3 = new Box();
calculateArea2(box2); // Calculate box 2
JOptionPane.showMessageDialog(null, " Second Box's area is: "+box3);
}
public static int calculateArea(Box k){
return k.length* k.width;
}
public static Box calculateArea2(Box k){
Box c = new Box();
c.area = c.length*c.area;
return c;
}
}
class Box{
int length;
int width;
int area;
}
なぜスキャナのコンストラクタ( 'new Scanner(str)')のパラメータとして文字列がありますか?とにかく、あなたの質問は全く明確ではありません。 – Gendarme
Boxオブジェクトをprintlnメソッドに渡すと、Boxオブジェクトの状態(長さ、幅、面積)を示すテキストが表示されるように、Boxクラスの 'public String toString()'メソッドをオーバーライドします。 –
@Gendarme Bc私が知っていることを繰り返したいのですが、古いレッスンをremmemberするのに役立ちます。 –