[英]Why doesn't my variable return the answer?
So I'm trying to construct a program. 所以我正在尝试构建一个程序。 Everything works but my math portion of the program.
一切正常,但程序的数学部分除外。 I want the time in mins entered to be converted to hours.
我希望将以分钟为单位的时间转换为小时。 This should be a decimal number like 30 mins=.5 hrs.
这应该是一个十进制数字,例如30分钟= .5小时。 I'll try to omit as much code as I can that I don't think is relevant to make it easier to read.
我会尽量省略我认为与简化阅读无关的代码。
public class StudentReader
{
private static String studentName= "";
private static int pages;
private static int time;
StudentReader(String name,int pagenum, int totalTime)
{
studentName=name;
pages=pagenum;
time=totalTime;
}
public double getTotalTimeInHours()
{
double total=0;
total=time / 60;
return total;
}
}
This class is being called by another class: 该类正在被另一个类调用:
System.out.println("What is the total amount of time spent reading?: ");
totalTime=scanner.nextInt();
System.out.println(StudentReader.getTotalTime());
This is one problem: 这是一个问题:
total=time / 60;
Both time
and 60
are int
values, so it uses integer division, and then promotes the result to a double
value in order to assign it to total
. time
和60
都是int
值,因此它使用整数除法,然后将结果提升为double
值,以便将其分配给total
。
This simple change will force it to use double
arithmetic: 这个简单的更改将迫使它使用
double
算法:
total=time / 60.0;
However, given that you don't actually do anything else with total
other than return it, the code would be simpler as: 但是,鉴于除了
total
除返回值外,您实际上不做其他任何事情,因此代码将更简单:
public double getTotalTimeInHours() {
return time / 60.0;
}
Additionally, as Leeish pointed out, you're trying to call it as getTotalTime
, which isn't the method name... 此外,正如Leeish指出的那样,您正在尝试将其称为
getTotalTime
,这不是方法名称...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.