如何在没有调用对象的情况下使用另一个类中定义的方法?

时间:2017-06-24 13:45:38

标签: java

我是Java新手,我试图从不同的公共类调用get方法。代码处理但是回答'返回" WineTempTime $ Winechiller @ 45ee12a7"由于某种原因,我无法弄清楚。

我的方法定义中是否存在问题,或者方法构造函数是否存在问题?感谢帮助!

以下是代码:

import java.util.Scanner;

public class WineTempTime {

public static void main(String[] args) {

   // code that inputs double wineTemp, preferedTemp, chillTemp here

        Winechiller answer = new Winechiller();
        answer.getChillingtime(wineTemp, preferedTemp, chillTemp);

        System.out.print("It takes " + answer + " minutes for wine to 
reach desired temperature.");
    }   
}

public static class Winechiller {

// constructors
static final double DELTA_MINUTES = 0.1;
static final int TAO = 50;
WineTempTime wineTemp = new WineTempTime();
WineTempTime preferedTemp = new WineTempTime();
WineTempTime chillTemp = new WineTempTime();
double timeCount = 0;

// equation for minutes until reaches temperature 
public int getChillingtime(double wineTemp, double preferedTemp, double 
chillTemp) {
    while (wineTemp > preferedTemp) {
        double tempDecrease = ( (wineTemp - chillTemp) / TAO ) 
        * DELTA_MINUTES;
        wineTemp -= tempDecrease;
        ++timeCount; }
    timeCount /= 10;
    Math.round(timeCount);
    int minutes = (int)timeCount;
    return minutes;     
    }
}
}

2 个答案:

答案 0 :(得分:1)

您应该打印方法answer.getChillingtime的结果,而不是answer

int minutes = answer.getChillingtime(wineTemp, preferedTemp, chillTemp);
System.out.print("It takes " + minutes + " minutes for wine to reach desired temperature.");

答案 1 :(得分:1)

在您的代码中,您已直接打印answer请勿直接打印。

打印为

 System.out.print("It takes " + answer.getChillingtime(wineTemp, preferedTemp, 
    chillTemp) + " minutes for wine to reach desired temperature.");

并且您调用函数getChillingtime()而不存储它因为它返回一个整数。 所以你排除了这行

 answer.getChillingtime(wineTemp, preferedTemp, chillTemp);

在您的程序中打印answer由于answerWinechiller类的对象,因此当您尝试打印answer时,您将获得答案对象的信息因为声明

System.out.println(answer);

转换为表格

 System.out.println(answer.toString());

其中toString()是Object类的方法,它是所有java类的超类。