-2

The code is as following:

    package zad;

    import java.util.*;

     public class zadaca_palindrom {
     public static void main(String[] args) {
        Scanner unos = new Scanner(System.in);
        System.out.println("Unesi recenicu:");
        String str = unos.next();
        String str1 = str.replaceAll("\\s+", "");
        System.out.println(str1);
    }}

When I enter a String, for example "My name is John Doe" I want my program to remove the white spaces. But when I run it it just outputs the first word of my string(in this case "My"). Any help is welcome! Thanks

  • 3
    `next()` reads only the next whitespace delimited token (i.e. "My"). Use `nextLine()` if you want the whole line. In the future, print out all the intermediate values when you run into this sort of problem. 99% of the time, the real issue is that your data isn't what you think it is. – azurefrog Nov 07 '19 at 18:19

1 Answers1

1

I believe you wanted to read the entire line and not only the first word. You should have used nextLine() instead of next()

public class zadaca_palindrom {
     public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Unesi recenicu:");
        String input = scanner.nextLine();
        String noSpacesInput = input.replaceAll("\\s+", "");
        System.out.println(noSpacesInput);
     }
}
Asaf Savich
  • 623
  • 1
  • 9
  • 29