[英]Recursive method return and print Int number of String
我在使用遞歸方法時遇到了麻煩。 這將返回並在我的主要方法中輸出W的X數。X是命令行上的正整數(arg [0]),W是命令行上的String(arg [1])。 因此,對於任何數字,它將多次打印字符串。
例如,我的第一個命令行參數是“ 4”,而我的第二個命令行參數是Hello。
輸出應打印為字符串:
“你好你好你好你好”
我的參數是整數和我相信的字符串時遇到問題:(?
我的代碼atm:
public static void main(String[] args){
int number = new Integer(0);
String word = new String("");
number = Integer.parseInt(args[0]);
word = args[1];
String method = recursive1.method1(word);
System.out.println(method);
}
public static String method1(String word, int number) {
if (number < 0){
return 0;
}
else{
return word + method1(number-1);
}
}
}
嘗試
public static String method1(String word, int number) {
if (number < 1){
return ""; // seems that if number is 0 or less, nothing will be printed
}
return word + method1(word, number-1);
}
要打印它:
System.out.println(method1(word, number));
您的代碼有幾個問題。 我在必要時添加了評論;
public static void main(String[] args) {
... // skipped previous lines
// No need to use class name as main is static and method1 is also static.
String method = method1(word, number); // Call the method with 2 parameters
System.out.println(method);
}
// With an else - improves readability
public static String method1(String word, int number) {
if (number == 0) { // If it is zero, return a blank string
return ""; // return a blank string and not 0(int)
} else {
return word + method1(word, number - 1); // method1 requires 2 parameters
}
}
// Without an else - unnecessary else removed
public static String method1(String word, int number) {
if (number == 0) { // If it is zero, return a blank string
return ""; // return a blank string and not 0(int)
}
// Removed the else as its really not necessary
return word + method1(word, number - 1); // method1 requires 2 parameters
}
附帶說明一下,在main()
方法中,您實際上有2行不必要的代碼行。
// int number = new Integer(0); // not needed
// String word = new String(""); // not needed
int number = Integer.parseInt(args[0]); // Since you're over-writing the value anyways
String word = args[1]; // Since you're over-writing the value anyways
你寫:
int number = new Integer(0);
最好是:
int number = 0;
還是為什么不
int number = Integer.parseInt(argv[0]);
馬上? 最初的0有什么用?
然后,當然,當您定義帶有n個參數的方法時,請始終使用n個參數來調用它。
String result = method1(word, number);
試試這個代碼。 需要進行一些更改。
public static void main(String[] args){
int number = new Integer(5); // you can comment this line when providing input from command line
String word = new String("hello");// you can comment this line when providing input from command line
number = Integer.parseInt(args[0]);
word = args[1];
String method = method1(word,number);
System.out.println(method);
}
public static String method1(String word, int number) {
if (number == 0){
return "";
}
else{
return word + method1(word,number-1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.