How can I call a Java method using the Terminal?

Viewed 106

have a problem with JAVA when try to call a method if the main execute from TERMINAL.

i have a simple Class A

public class A{
   public static int promedio(ArrayList<Integer> array) {
       int sum=0,prom=0;
       for(int i=0 ; i < array.size() ; i++) {
           sum+=array.get(i);}
       prom = sum/array.size();
       return prom;
   }
}

And Iam try to call method promedio() from Class B


public class B{

    public static void main(String[] args) {
        ArrayList<Integer> array = new ArrayList<Integer>();
       
        //Convert to int the string from args
        for (int i = 0; i < args.length; i++) {
            int StrToInt= Integer.parseInt(args[i]);
            array.add(StrToInt);
            }
        //call method class A
        int returnPromedio = A.promedio(array);

        System.out.println("Prom: "+returnPromedio);
        
        }
}

when try to run from TERMINAL with java B.java 200 100

Get this error:

B.java:13: error: cannot find symbol
        int returnPromedio = A.promedio(array);
                             ^
  symbol:   variable A
  location: class B
1 error
error: compilation failed

What I can do to run this code from TERMINAL, thanks everyone!!

3 Answers

Your code works. Compile it and then change your dir in the command line to where your classes are located. Run this command in the screen shot:

enter image description here

I copied your classes, compiled both of them, and executed from command line as you mentioned.

enter image description here

The problem was a try to run B.java on src folder...

I need to run B.class from bin folder,

Finally move to bin folder and run:

java B 200 100

Works OK!!

Related