im new to java and am writing a program that will let you input your first and last name and will give you your initials, but i want the intitials to always be in upper case.
I get a "char cannot be dereferenced" error whenever i run the code.
import java.util.*;
public class InitialHere
{
public static void main (String[] args)
{
Scanner getInput = new Scanner (System.in);
String firstName;
String lastName;
char firstInitial;
char lastInitial;
System.out.println("What is your first name?");
System.out.println();
firstName = getInput.nextLine();
System.out.println();
System.out.println("Thankyou, what is your last name?");
System.out.println();
lastName = getInput.nextLine();
firstInitial = firstName.charAt(0);
lastInitial = lastName.charAt(0);
firstInitial = firstInitial.toUpperCase();
lastInitial = lastInitial.toUpperCase();
System.out.println();
System.out.println("Your initials are " + firstInitial + "" + lastInitial + ".");
}
}
In Java, primitives have no methods, only their boxed types do. If you want to get the uppercase version of a char
, the Character
class has a method just for that: Character.toUpperCase
:
firstInitial = Character.toUpperCase(firstInitial);
(Do the same for lastInitial
)
firstInitial
is of type char
which has no method toUpperCase
. (Being a primitive, it has no methods at all.) Call toUpperCase
on the original String
instead.
Update (see comments): The documentation of Character.toUpperCase
says:
In general,
String.toUpperCase()
should be used to map characters to uppercase.String
case mapping methods have several benefits overCharacter
case mapping methods.String
case mapping methods can perform locale-sensitive mappings, context-sensitive mappings, and 1:M character mappings, whereas theCharacter
case mapping methods cannot.
Therefore, the most robust approach would be to use
String firstName = firstName.trim(); // ignore leading white space
final String firstInitial = firstName.substring(0, firstName.offsetByCodePoints(0, 1)).toUpperCase();
Another solution:
firstInitial = (char) (firstInitial >= 97 && firstInitial <= 122 ? firstInitial - 32 : firstInitial);
lastInitial = (char) (lastInitial >= 97 && lastInitial <= 122 ? lastInitial - 32 : lastInitial);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.