问题
I am trying to reverse a sentence using recursion and print it out backwards. Right now after it prompts me to type in a sentence, it does not allow me to enter any input and ends. Is there something wrong with sc.nextLine()? How do I input a sentence as a string.
private static void testNum3()
{
System.out.print("Type in a sentence:");
String sentence= sc.nextLine();
System.out.println(reverse(sentence));
}
public static String reverse (String sentence)
{
if (sentence.length()== 0)
return sentence;
return reverse(sentence.substring(1)) + sentence.charAt(0);
}
回答1:
I use sc.next() elsewhere. Do they all have to be the same?
No, but you have to take care to handle the EOL or "End-Of-Line" token properly. If you call sc.next() and leave a dangling EOL token, it will be "swallowed" next time you call sc.nextLine() preventing you from getting input.
One solution: call sc.nextLine() when you need to handle the EOL token.
For instance, if you're getting an int from the user and its the only thing entered on the line, sometimes you must do:
int myVar = sc.nextInt();
sc.nextLine(); // swallow dangling EOL token with this call
// now you can safely call this below
String myString = sc.nextLine();
回答2:
just give it a try
import java.io.IOException;
import java.util.Scanner;
public class CoreJavaTest {
public static void main(String[] args) throws IOException {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
String sentence = "";
while (true) {
System.out.print("Enter sentence:");
sentence = sc.nextLine();
if (sentence.equals("exit")) {
System.out.println("Exiting...");
break;
}
reverse(sentence);
System.out.println("");
}
}
public static void reverse(String args) {
if (args.length() != 0) {
System.out.print(args.charAt(args.length() - 1));
reverse(args.substring(0, args.length() - 1));
}
}
}
来源:https://stackoverflow.com/questions/29403565/reversing-a-sentence-using-recursion-in-java