2

I'm trying to use a method to calculate y for all values between 1 and x of a given x for straight lines.

I want the values for y to be placed in an array and returned to the main method. When I run my program all values in the array are 0; where have I gone wrong?

Thanks!

import java.util.Scanner;
public class HelloWorld {
    public static void main(String [] args)
        {
            int n=0;
            int k=0;
            int m=0;
            Scanner in = new Scanner(System.in);

            System.out.println("Value of x: ");
            n = in.nextInt();

            int line[] = new int [n];
            System.out.println("value of k: ");
            k = in.nextInt();

            System.out.println("Value of m: ");
            m = in.nextInt();

            calcLine(n,k,m);
            for(int i = 0; i < line.length; i++){ 
                System.out.println(line[i]);  
            }
        }

    public static int[] calcLine(int n, int k, int m)
    {
        int[] line = new int[n];

        for (int i=0; i<line.length;i++){
            line[i] = (int) (k * i + m);
        }

        return line;
    }
}

4 Answers 4

6

Your main method has a different array called line than the one your calcLine method populates.

You should assign the returned array of your calcLine method to the line variable of your main method :

line = calcLine(n,k,m);
Sign up to request clarification or add additional context in comments.

Comments

0

you should assign calcLine(n,k,m); to line

Comments

0

The line in your calcLine method and the one in your main method are completely separate. You need to assign the value of line to the return value of the calcLine function.

Get rid of the declaration of line in main (int line[] = new int [n];) and change the method call line to:

int line[] = calcLine(n,k,m);

Comments

0

Your calcLine method is using a local variable (line) and performing all calculations in it. Then you return this variable, but in the code of your main function it is not stored anywhere.

Replace the line

calcLine(n,k,m);

with

line = calcLine(n,k,m);

Local variables are only alive in the scope where declared. This "line" inside calcLine is not the same "line" in the main caller function. When you return it, you must store the result of calcLine in line and then use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.