//method I'm trying to call
static String sentenceReversal(String input) {
int x = input.indexOf(" ");
//Base Case
if(x == -1)
return input;
//Recursive Method
return sentenceReversal(input.substring(x+1)) +" "+ input.substring(0, x);
case 6:
System.out.println("Enter a string to reverse:");
String input6 = scan.next();
System.out.println(sentenceReversal(input6));
break;
Calling the method as sentenceReversal("Hello World")
returns World Hello, but calling it with input6 returns Hello and nothing else, any ideas?
I made a specific scanner only for this case as well because I was previously getting a InputMismatchException
Also when after inputting a number after the switch the next part of the string appears.
>Solution :
Solution:
Use nextLine() method instead of next() method.
Reason:
next() method is used to input String containing only 1 word whereas nextLine() method is used to input String containing multiple words. This is the reason your code is returning ‘Hello’ instead of ‘World Hello’ because it is taking only ‘Hello’ as the input and ignoring ‘ World’
Your updated code:
case 6:
System.out.println("Enter a string to reverse:");
String input6 = scan.nextLine();
System.out.println(sentenceReversal(input6));
break;
Refer more methods of Scanner class at the below page:
https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/java/util/Scanner.html#method_summary