我有运行得很好的代码,但是我希望用户自己执行此操作,而不是为对象输入变量。但是我不知道该怎么做。
在演示/驱动程序中演示该类,该程序要求用户输入两块土地的尺寸。该程序应演示toString方法,以显示每个土地段的尺寸和面积,并使用equals方法指示这些土地段的大小是否相等,即土地段的面积相同。
对象类:
font-family
主要方法:
public class MitchellLandTract
{
private int length;
private int width;
private int area;
/**
* Constructor
* @param l length
* @param w width
*/
public MitchellLandTract(int l, int w)
{
length = l;
width = w;
}
/**
* toString for the land tract
* @param str the string describing the object
*/
public String toString()
{
// Create a string describing the land tract.
String str = "With the width, " + width +
", and the length, " + length +
". The area is " + area;
// Return the string.
return str;
}
/**
* getLength method
* @return area of land tract
*/
public double getArea()
{
area = length * width;
return area;
}
/**
* equals method
* @param object2 the object being compared to original
* @return if the areas are the same or different
*/
public boolean equals(MitchellLandTract object2)
{
boolean status;
// Determine whether this object's area field
// is equal to object2's area field
if (getArea()==object2.getArea())
status = true; // Yes, the objects are equal.
else
status = false; // No, the objects are not equal.
// Return the value in status.
return status;
}
答案 0 :(得分:0)
尝试
import java.util.Scanner;
方法主要
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Input Land 1");
int land1_A_Input = scan.nextInt();
int land1_B_Input = scan.nextInt();
System.out.println("Input Land 1");
int land2_A_Input = scan.nextInt();
int land2_B_Input = scan.nextInt();
// Create two MitchellLandTract objects with the same values
MitchellLandTract land1 = new MitchellLandTract(land1_A_Input, land1_B_Input);
MitchellLandTract land2 = new MitchellLandTract(land2_A_Input, land2_B_Input);
// Use the equals method to compare the objects
if (land1.equals(land2))
System.out.println("Both objects are the same.");
else
System.out.println("The objects are different.");
// Display the objects' values
System.out.println("For the first tract of land: " + land1);
System.out.println("For the second tract of land: " + land2);
}
输出
Input Land 1
4 5
Input Land 1
10 5
The objects are different.
For the first tract of land: With the width, 5, and the length, 4. The area is 20
For the second tract of land: With the width, 5, and the length, 10. The area is 50