鉴于我的程序如下,我对返回行在方法中实际执行的操作感到有些困惑。无论我放在哪个变量,当我在主类中调用方法时,它仍然返回相同的值。在任何不是void的方法中,使用return(变量名)做了什么呢?您是否应该为方法标题中的每个变量列出一个return语句?对不起,我只是想了解方法。还有,请你批评我的整体计划。是否有意义?看起来写得好吗?谢谢!
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int seconds=0, minutes=0, hours=0, days=0;
System.out.println("We will convert seconds to minutes hours and days!");
System.out.println("How many conversions would you like to do?");
Scanner keyboard = new Scanner(System.in);
int conversion =keyboard.nextInt();
for (int count = 1; count <= conversion; count++)
{
Calculator.convert();
}
}
public static void convert()
{
System.out.println("Enter seconds: ");
Scanner keyboard = new Scanner(System.in);
double seconds, minutes, hours, days;
seconds = keyboard.nextInt();
minutes = seconds/60.0;
hours = minutes/60.0;
days = hours/24.0;
System.out.println("Minutes: " + minutes + " Hours: " + hours + " Days: " + days);
}
}
答案 0 :(得分:2)
您不需要在方法中使用退货,因为您不能使用它。返回值用于将值返回给调用函数的程序。例如,如果你想要回到&#34;天&#34;值,您应该调用这样的方法:
double days = Calculator.convert(seconds, minutes, hours, days);
但是,如果您不需要在程序中返回由该方法生成的值,则您的方法应该不返回任何内容。关键字&#34; void&#34;没有指定任何内容。例如:
public static void convert(double seconds, double minutes, double hours, double days)
{
System.out.println("Enter seconds: ");
Scanner keyboard = new Scanner(System.in);
seconds = keyboard.nextInt();
minutes = seconds/60.0;
hours = minutes/60.0;
days = hours/24.0;
System.out.println("Minutes: " + minutes + " Hours: " + hours + " Days: " + days);
}