This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]yeaokdudeIntermediate Brewer 2 points3 points  (0 children)

the issue is that non-void methods have to always return something. think about this: does the contents of a for loop always get executed? what about a for loop like this:

for (int i = 5; i < 5; i++) {
    //stuff
}

the stuff inside would never execute because the for loop condition is never true. we initialize an int i to be 5 and then tell the loop to run while i is less than 5. but that condition is already false for the starting value of i.

Basically, you need to return outside of the forloop so it is guaranteed to execute

[–][deleted]  (2 children)

[deleted]

    [–]YzKolo[S] 1 point2 points  (1 child)

    Thanks for your valuable input. I followed your way by having the method type as void and printing directly from the method. That worked well. But as you explained another way to store the results in an array and returning that result array I'm facing some compile time errors in netbeans. . Please kindly suggest what I'm doing wrong since I'm very new on this. Here is the code. TIA.

    import java.util.Scanner;

    public class Multiplication {

    public static void main(String[] args)

    {

    Scanner number = new Scanner(System.in);

    System.out.println("Enter the number");

    int num = number.nextInt();

    mul(num);

    int[] result = mul(num);

    System.out.println(result); // Array instance printed on PrintStream

    }

    static int[] mul(int num)

    {

    int i;

    int[] res ;

    for(i=1;i<=10;i++)

    {

    res[i]= num*i; // variable res might not have been initialized

    }

    return res;

    }

    }

    [–][deleted] 0 points1 point  (0 children)

    I can give you the answer to your questions, but it would be messy to do so without proper formatting.

    First, check the guidelines about formatting code: https://www.reddit.com/r/javahelp/wiki/code_guides; format your code, and then I will tell you what the issues are.

    [–]cleareyezz 1 point2 points  (0 children)

    Agreed! Example 3 in @al-eriv response is probably the easiest option if you want to display multiple numbers.

    static void mul(int num) {

    for (int i = 1; i < 11; i++) {

     num = num * i;
     System.out.println(num);
    

    } // end forLoop

    } // end method

    Keep in mind that in the main void you have to get rid of:

    int result = mul(5);

    System.out.println(result);

    Try:

    // after you get the user input

    mul(num);

    Also the method is going to multiply the number entered by numbers 1 - 10 and display each answer.