0

In this exercise I am to reverse a string. I was able to make it work, though it will not work with spaces. For example Hello there will output olleH only. I tried doing something like what is commented out but couldn't get it to work.

import java.util.Scanner;

class reverseString{
  public static void main(String args[]){
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String input = scan.next();
    int length = input.length();
    String reverse = "";
    for(int i = length - 1; i >= 0; i--){
        /*if(input.charAt(i) == ' '){
            reverse += " ";
        }
        */
        reverse += input.charAt(i); 
    }
    System.out.print(reverse);
}
}

Can someone please help with this, thank you.

2 Answers 2

2

Your reverse method is correct, you are calling Scanner.next() which reads one word (next time, print the input). For the behavior you've described, change

String input = scan.next();

to

String input = scan.nextLine();
Sign up to request clarification or add additional context in comments.

1 Comment

Oh thank you. I am familiar with nextLine() already should had though of that.
0

You can also initialize the Scanner this way:

Scanner sc = new Scanner(System.in).useDelimiter("\\n");

So that it delimits input using a new line character.

With this approach you can use sc.next() to get the whole line in a String.

Update

As the documentation says:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

An example taking from the same page:

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close(); 

prints the following output:

1
2
red
blue

All this is made using the useDelimiter method.

In this case as you want/need to read the whole line, then your useDelimiter must have a pattern that allows read the whole line, that's why you can use \n, so you can do:

Scanner sc = new Scanner(System.in).useDelimiter("\\n");

1 Comment

I am unfamiliar with the delimiter. what exactly is happening here, why use the \n and not a symbol for a space?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.