Search code examples
javabluej

Java - for loop currentTimeInMillis() - BlueJ


I'm learning Java at the moment, i'm using BlueJ to write a method that returns currentTimeInMillis() while y < 100. At the moment i'm receiving an error stating "missing return statement". Any suggestions re the 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());

}


} 

Solution

  • All you need to do is to add a return statement in the end:

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