Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 593
Ilja Avatar asked Apr 14 '26 10:04

Ilja


1 Answers

The problem is because of whitespace as all the indices you refer while converting to uppercase are not accurate. So first trim() the String so you can clear all leading and trailing whitespace and then capitalize it. better check empty string and all whitespace to avoid exception.

String askWork = input.nextLine().trim();
String capitalized = askWork.substring(0, 1).toUpperCase() + askWork.substring(1)
like image 112
Brij Avatar answered Apr 16 '26 01:04

Brij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!