Question:
I have a very simple question that I do not know if it can be done as I think, and I feel if the question is too obvious for you, I am starting to program.
I have the following code:
String nombre;
System.out.println("Nombre:");
nombre=in.nextLine();
Is there a way that when collecting name, it automatically transforms it with the first letter in uppercase and the others in lowercase?
So if I enter aLberTo
, the program actually picks up Alberto
.
Greetings and thanks in advance.
Answer:
This is a quick way, getting the character in the first position using the charAt () method and converting it to uppercase using toUpperCase () :
nombre.toUpperCase().charAt(0)
you concatenate this value to the original string value, removing the first character, which is the one you previously converted to uppercase, using the substring () method:
nombre.substring(1, nombre.length()) //Elimina el primer carácter.
This would be an example:
String nombre = "leopard56";
String resultado = nombre.toUpperCase().charAt(0) + nombre.substring(1, nombre.length()).toLowerCase();
System.out.println("resultado : " + resultado );
the output would be:
resultado : Leopard56
To perform the transformation directly on the line,
nombre=in.nextLine();
you can use a method;
public static String toMayusculas(String valor) {
if (valor == null || valor.isEmpty()) {
return valor;
} else {
return valor.toUpperCase().charAt(0) + valor.substring(1, valor.length()).toLowerCase();
}
}
and call it before storing the value
nombre = toMayusculas(in.nextLine());