I have only started writing in java and wrote this program:
public class FibonacciWord{
public static void main(String[] args){
if (args.length < 3) System.exit(1);
int N=Integer.parseInt(args[2]);
System.out.println(fibonacci(N,args[0],args[1]));
}
}
public String fibonacci(int N, String a, String b){
if (N==0) return a;
return fibonacci(N-1,a+b,a);
}
And then I try to compile it gives a number of errors, the first is:
FibonacciWord.java:9 : error: class, interface, or enum expected
public String fibonacci(int N, String a, String b){
^
What is wrong here?
您在类之外声明方法“ fibonacci”。
Your method is not in a class. It should be like this:
public class FibonacciWord{
public static void main(String[] args){
if (args.length < 3) System.exit(1);
int N=Integer.parseInt(args[2]);
System.out.println(fibonacci(N,args[0],args[1]));
}
public String fibonacci(int N, String a, String b){
if (N==0) return a;
return fibonacci(N-1,a+b,a);
}
}
You should put your method inside the class:
public class FibonacciWord{
public static void main(String[] args){
if (args.length < 3) System.exit(1);
int N=Integer.parseInt(args[2]);
System.out.println(fibonacci(N,args[0],args[1]));
}
public static String fibonacci(int N, String a, String b){
if (N==0) return a;
return fibonacci(N-1,a+b,a);
}
}
And to make it work you should make it static
. Or you can create new FibonacciWord
object and call this method from it, like so inside main
:
FibonacciWord solution = new FibonacciWord();
solution.fibonacci(N,args[0],args[1]);
You method is outside the Main class, place it inside.
You have to make it static
in order to call it from the main method.
public class FibonacciWord{
public static void main(String[] args){
if (args.length < 3) System.exit(1);
int N=Integer.parseInt(args[2]);
System.out.println(fibonacci(N,args[0],args[1]));
}
public static String fibonacci(int N, String a, String b){
if (N==0) return a;
return fibonacci(N-1,a+b,a);
}
}
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.