簡體   English   中英

如何將值從一個類返回到另一個類?

[英]How do I return values from one class to another?

我只需要將儲蓄值返回給主類的調用方法即可。 我擴展了子類,但它不起作用。 我也嘗試將子類作為對象導入到父類中,仍然沒有成功。

package package1;

import java.util.Scanner;

public class GnX {
   FvX fvx = new FvX( );    
         
   public static void main(String[] args) {
        double price;
        double discount;
        double savings;
        Scanner scan = new Scanner(System.in);  
        
        
        System.out.println("Enter a base price for the discount: ");
        price = scan.nextDouble( );
        System.out.println("Now, Enter a discount rate: ");
        discount = scan.nextDouble( );
    
        displayInfo( );
        computeDiscountInfo( );
    
        System.out.println("Special this week on any service over " + price);
        System.out.println("Discount of " + discount);
        System.out.println("That's a savings of at least $" + savings);
    }

    public static void displayInfo( ) {
        System.out.println("Paradise Guitar Is A Fantastic Place To Reherse"); 
        System.out.println("This Rehersal Room Is Studio Based");
    }
}

在單獨的窗口中通過父類繼承的類:


package package1;

public class FvX extends GnX {

    public FvX( ) {
    }
    
    public static double computeDiscountInfo(double price, double discount) {
        double savings;
        savings = price * discount / 100;
        return savings;
    }
}

假設您想要使用computeDiscountInfo 這屬於fvx對象,所以它應該被稱為fvx.computeDiscountInfo(...)

現在考慮

  1. 它返回一個 double,所以你可以做double rv = fvx.computeDiscountInfo(...)
  2. 你注意到我寫了(...) ,因為這個方法需要幾個參數double price, double discount 所以你應該調用使用參數而不是...也許double rv = fvx.computeDiscountInfo(price, discount);

您要做的是從您的 main 方法調用 FvX 類中的 computeDiscountInfo 函數。

首先在您的 main 方法中創建一個 FvX 實例,然后使用該 fvx 對象調用 computeDiscountInfo 函數。 您可以像下面顯示的那樣替換主類。

public class GnX {

    public static void main(String[] args) {

        FvX fvx = new FvX( );

        double price;
        double discount;
        double savings;

        Scanner scan = new Scanner(System.in);


        System.out.println("Enter a base price for the discount: ");
        price = scan.nextDouble( );
        System.out.println("Now, Enter a discount rate: ");
        discount = scan.nextDouble( );


        displayInfo( );
        savings = fvx.computeDiscountInfo(price, discount);


        System.out.println("Special this week on any service over " + price);
        System.out.println("Discount of " + discount);
        System.out.println("That's a savings of at least $" + savings);
    }


    public static void displayInfo( ) {
        System.out.println("Paradise Guitar Is A Fantastic Place To Reherse");
        System.out.println("This Rehersal Room Is Studio Based");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM