[英]What am I doing wrong with my code? Translating into PigLatin and cant figure out how to print returned value
[英]Wrong output being displayed, I cant figure out my mistake
我希望我的程序顯示正方形和矩形的區域,因為您可能已經猜到這是一個家庭作業問題,所以我無法真正更改格式。
import java.util.*;
abstract class Shape
{
int area;
abstract void area();
}
class Square extends Shape
{
int len;
void area()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the lenght of the square: ");
len=s.nextInt();
}
public void displayarea()
{
Square q= new Square();
q.area();
System.out.println("The area of the square is: "+(len*len));
}
}
class Rectangle extends Shape
{
int l,b;
public void area()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the lenght of the rectangle: ");
l=sc.nextInt();
System.out.println("Enter the breadth of the rectangle: ");
b=sc.nextInt();
}
public void displayarea()
{
Rectangle r = new Rectangle();
r.area();
System.out.println("The area of the rectangle is: "+(l*b));
}
}
public class Postlab
{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle();
Square square = new Square();
rectangle.displayarea();
square.displayarea();
}
}
在您的代碼displayarea()
方法中,您正在創建 Class (Square/Rectangular) 的新 Object 以調用area()
方法。 因此,掃描儀使用 area() 方法為其分配值的對象與您打印該區域的對象不同。 所以技術上area()
和displayarea()
是在 class 的不同對象上調用的。 所以你總是得到 null 或 0。在一個 object 中分配的數據不被另一個對象共享。 (直到變量未聲明為 static、static 變量在類的所有實例之間共享)
所以你的代碼應該更新如下(同樣適用於矩形):
public void displayarea() {
area();
System.out.println("The area of the square is: " + (len * len));
}
問題是您在錯誤的 object 上調用區域。
public void displayarea() {
Square q = new Square();
q.area();
System.out.println("The area of the square is: " + (len * len));
}
當您在正方形 A 上調用它時,它首先創建一個正方形 B 並調用 B.area()。 因此,當您進行面積計算時,結果為 0。所有值都設置在正方形 B 上,而正方形 A 的值保持未設置。
相反,您想調用正方形 A 上的區域。像這樣。
public void displayarea() {
area();
System.out.println("The area of the square is: " + (len * len));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.