2 回答
TA贡献1821条经验 获得超4个赞
您不需要在功能中传递扫描仪。从用户那里获取输入并将其传递给递归函数。首先传递字符串,起始索引和最后一个索引。这是代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence and I will reverse it : ");
String line = input.nextLine();
String reverse = reverseLine(line, 0, line.length() - 1);
System.out.println(reverse);
}
Reverseline 函数接受一个输入并在指定位置交换输入字符并递归调用。
public static String reverseLine(String input, int startIndex, int endIndex) {
if (startIndex >= endIndex) {
return input;
} else {
input = swap(input, startIndex, endIndex);
return reverseLine(input, startIndex + 1, endIndex - 1);
}
}
这个函数只交换字符串的字符。
public static String swap(String input, int start, int end) {
char[] arr = input.toCharArray();
arr[end] = input.charAt(start);
arr[start] = input.charAt(end);
return String.valueOf(arr);
}
TA贡献1802条经验 获得超5个赞
import java.util.Scanner;
public class ReverseTry {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence and I will reverse it");
reverseLine(input); //no need to pass Scanner object as input to method since the return value isn't used anyway
}
public static Scanner reverseLine(Scanner input) {
if (!input.hasNextLine()) {
return input;
} else {
//String word = input.nextLine();
//return reverseLine(input) + " " + word;
String line = input.nextLine();
reverseLine(input); // after you get the line over here,
//this function will be called again.
//In the recursively called function,
//it will again ask you for input and
//once you give it, again call itself
//and this will go on forever. Instead
//of this endless recursive call, you
//need to give a base condition on which
//this method should return a useful value
//without calling itself. For example, you
//know that there is nothing to be
//reversed in a single character string ...
System.out.println(line);
}
return input;
}
}
你可能想要像下面这样的东西,
import java.util.*;
public class ReverseTry {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence and I will reverse it");
String s = input.nextLine(); //no need to pass Scanner object into the reverseline method. Scanner object is used to read the console input only once
s = reverseLine(s); // here is where the reversing logic goes
System.out.println(s); // printing out the reversed string
}
public static String reverseLine(String s) {
if(s.length() == 1 ) { //base case --> there is nothing to reverse when the string length is 1
return s;
}
return s.substring(s.length()-1)+reverseLine(s.substring(0,s.length()-1)); //recursion logic
}
}
添加回答
举报