Java - 循环 currentTimeInMillis() - BlueJ

Java - for loop currentTimeInMillis() - BlueJ

我目前正在学习 Java,我正在使用 BlueJ 编写一个 returns currentTimeInMillis() while y < 100 的方法。目前我收到一个错误说明 "missing return statement"。对 error/code 有什么建议吗?

import java.lang.System;

public class Math
{
// instance variables - replace the example below with your own
private int y;

/**
 * Constructor for objects of class Math
 */
public Math()
{
    // initialise instance variables
    y = 0;
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public static long currentTimeMillis()
{
    // put your code here

    for (int y = 0; y<100; y++)
    {return y;
    }

    System.out.println(System.currentTimeMillis());

}


} 

您的 currentTimeMillis 应该 return 多头。这个签名

public static long currentTimeMillis()

说明您的 privatestatic 方法必须 return 类型为 long.

作为编码者,您可以假设 for 循环将始终执行,但编译器不能,这就是为什么您必须在方法末尾添加 return 语句的原因。不过我会重构整个方法...

你需要做的就是在最后添加一条return语句:

public static long currentTimeMillis()
{
    // put your code here
    for (int y = 0; y<100; y++)
    {
      return y;  // This code does not make sense as it will always return 0
    }
    System.out.println(System.currentTimeMillis());

    // from the function name it appears you want to return current time millis

    return System.currentTimeMillis();

}