java 如何将值从一个类返回到另一个类?

enyaitl3  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(221)

我只需要返回一个值,这个值是主类的call方法的节省值。我扩展了子类,但是它不起作用。我也尝试过将子类作为对象导入到父类中,仍然没有成功。

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;
    }
}
sbdsn5lh

sbdsn5lh1#

假设你想使用computeDiscountInfo,它属于fvx对象,所以应该被称为fvx.computeDiscountInfo(...)
现在想想
1.它返回一个双精度值,所以可以执行double rv = fvx.computeDiscountInfo(...)
1.你注意到我写了(...),因为这个方法有两个参数double price, double discount,所以你应该使用参数来调用,而不是...,也许是double rv = fvx.computeDiscountInfo(price, discount);

vx6bjr1n

vx6bjr1n2#

您要做的是从main方法调用FvX类中的computeDiscountInfo函数。
首先在main方法中创建一个FvX示例,然后使用该fvx对象调用computeDiscountInfo函数。你可以如下所示替换你的main类。

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");
    }
}

相关问题