Search code examples
javareplaceallcapitalize

Remove whitespaces and capitalize user input


I've made the code so it asks the user various questions, and if the input.trim().isEmpty() a message will be given to the user and will ask the user to input again. So if the user just writes blank spaces, message given. If the user gives a few blank spaces and some characters, it will accept.

Problem right now is that I want to capitalize the first letter of the Word, but it doesn't really work. Say if the user's input start with a letter then that will be capitalized. But if there's whitespace it wont capitalize at all.

So if input is:

    katka

Output is:

katka

Another example:

katka

Output is:

Katka

Code is:

String askWork = input.nextLine();

String workplace = askWork.trim().substring(0,1).toUpperCase()
 + askWork.substring(1);

while (askWork.trim().isEmpty()){ String askWork = input.nextLine();

String workplace = askWork.trim().substring(0,1).toUpperCase()
 + askWork.substring(1);

}

I've tried different approaches but no success.


Solution

  • The trim() method on String will clear all leading and trailing whitespace. The trimmed String must become your new String so that all indices you refer to after that are accurate. You will no longer need the replaceAll("\\s",""). You also need logic to test for empty input. You use the isEmpty() method on String for that. I've written a toy main() that keeps asking for a word and then capitalizes and prints it once it gets one. It will test for blank input, input with no characters, etc.

     public static void main(String[] args) throws Exception {
    
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    
            String askWork = "";
            while (askWork.isEmpty()) {
                System.out.println("Enter a word:");
                askWork = input.readLine().trim();
            }
    
            String workPlace = askWork.substring(0,1).toUpperCase() + askWork.substring(1);
    
            System.out.println(workPlace);
        }