[英]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. args
是main
方法的本地String
数组。
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
.所以首先它是
main
方法的一个局部变量,它在解释第一个错误的calculate
方法中不可见: error: cannot find symbol
。
Secondly calculate
expects a long
parameter and your are trying to supply a String
.其次
calculate
需要一个long
参数,而您正试图提供一个String
。 For that you are getting error: method calculate in class Test cannot be applied to given types;
为此,您收到
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.因此,将
args[0]
转换为long
作为参数后,将其传递给calculate
。
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.在整个类中,没有使用命名args定义的实例变量,您尝试使用的变量是 main 方法中的参数,只能在 main方法中访问。
By considering your code your doing nothing inside calculate so you can write main method as follows:通过考虑您的代码,您在计算内部什么都不做,因此您可以按如下方式编写 main 方法:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.