简体   繁体   中英

Can’t figure out how to Return a value

This will probably will get down voted, so if you do down vote me, can you provided a link to where I can find this?

What am I doing wrong here? I am very new and it seems like this should work. I just don't know what I am doing wrong. This is my error

public class Test
{
    public static long calculate(long n)
    {   
        n = args[0];
        return n;
    }   
    public static void main(String[] args)
    {       
        long answer;
        answer = calculate();       
    }   
}

Exception:

Test.java:6: error: cannot find symbol
                n = args[0];
                    ^
  symbol:   variable args
  location: class Test
Test.java:13: error: method calculate in class Test cannot be applied to given types;
                answer = calculate() ;
                         ^
  required: long
  found: no arguments
  reason: actual and formal argument lists differ in length
2 errors

args is a String array local to the main method.

So firstly it is a local variable of the main method and it is not visible inside the calculate method which explains the first error: error: cannot find symbol .

Secondly calculate expects a long parameter and your are trying to supply a String . For that you are getting error: method calculate in class Test cannot be applied to given types;

So pass args[0] to the calculate after converting it to long as a parameter.

public class Test
{
    public static long calculate(long n)
    {   
        return n;
    }   
    public static void main(String[] args)
    {       
        long answer = 0L;
        try{
            answer = calculate(Long.parseLong(args[0]));
        }catch (ArrayIndexOutOfBoundsException ae){
            ae.printStackTrace();
        }catch (NumberFormatException nfe){
            nfe.printStackTrace();
        }
        System.out.println(answer);      
    }   
}

In whole class there is no instance variable defined with named args , variable which you are trying to use is a parameter in main method and accessible only inside main method.

By considering your code your doing nothing inside calculate so you can write main method as follows:

 public static void main(String[] args)
    {       
        long answer;
        answer = Long.parseLong(args[0]);       
    }  

Both code will do same work.

Below code can solve your issue

public class Test
{
    public static long calculate(String[] args)
    {
        long n = Long.parseLong(args[0]);
        return n;
    }
    public static void main(String[] args)
    {
        long answer;
        answer = calculate(args);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM