gpt4 book ai didi

java - Java 中的返回类型(请批评)

转载 作者:行者123 更新时间:2023-12-02 06:08:44 25 4
gpt4 key购买 nike

鉴于我的下面的程序,我对返回行在方法中实际执行的操作有点困惑。无论我在那里放置什么变量,当我在主类中调用该方法时,它仍然返回相同的值。在非 void 的方法中使用 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);


}


}

最佳答案

您不需要在方法中使用 return,因为您不使用它。返回用于将值返回给调用函数的程序。例如,如果您想返回“天”值,您应该调用如下方法:

double days = Calculator.convert(seconds, minutes, hours, days);

但是,如果您不需要在程序中返回该方法生成的值,则您的方法应该不返回任何内容。关键字“void”没有指定任何内容。例如:

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

关于java - Java 中的返回类型(请批评),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22061764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com