Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my method not work when I input a variable vs. inputting a string directly?

//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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading