user8467661
user8467661

Reputation:

can variable declared in main be accessed from static function?

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int simpleArraySum(int n, int[] ar) {
        // Complete this function
        for(int ar_i = 0; ar_i < n; ar_i++){
            result = result +ar[ar_i];
            return result;  
        }

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] ar = new int[n];
        for(int ar_i = 0; ar_i < n; ar_i++){
            ar[ar_i] = in.nextInt();
        }
         int result = simpleArraySum(n, ar);
         System.out.println(result);

    }
}

error log

Solution.java:13: error: cannot find symbol
            result = result +ar[ar_i];
            ^
  symbol:   variable result
  location: class Solution
Solution.java:13: error: cannot find symbol
            result = result +ar[ar_i];
                     ^
  symbol:   variable result
  location: class Solution
Solution.java:14: error: cannot find symbol
            return result;
                   ^
  symbol:   variable result
  location: class Solution
3 errors

This program is suppose to print the sum of the elements in an array. i have no idea how to access variable declared in main from the static function. what am i doing wrong?

Upvotes: 2

Views: 228

Answers (1)

azro
azro

Reputation: 54148

The variable result does not exists in simpleArraySum() method because it is defined in the scope of the main

You may create a variable in the method which will do the sum and return it, and it will be stored in result int the main

Also you need to put the return sum; AFTER the loop, if you don't, it will do the 1st iteration and then return the result and it's the end, you need to do all the loop and after return the sum, like this :

static int simpleArraySum(int n, int[] ar) {
    int sum = 0;
    for(int ar_i = 0; ar_i < n; ar_i++){
        sum = sum +ar[ar_i];      
    }
    return sum;
}

Tips (you don't need to use them, they are only INFORMATIVE):

you can also use a for each loop, which means for each int in the array ar, called intInLoop we'll do this

for (int intInLoop : ar){
      sum = sum + i;
}

And sum = sum +ar[ar_i]; is same as sum += ar[ar_i];

Upvotes: 2

Related Questions