Reputation: 12317
What I have is a student with a name and firstletter
So I have a class student like:
private String name = "Unknown";
private char nameLetter = "u";
public void identify()
{
System.out.println("Student first letter : " + nameLetter);
System.out.println("Student name : " + name);
}
public void setName(String newName)
{
name = newName;
nameLetter = newName.substring(0);
}
But i get the error cant convert from string to char.
I know I could make a String nameLetter instead of char but I want to try it with char.
Upvotes: 1
Views: 290
Reputation: 234685
"u"
is a string literal, 'u'
a char.
Specifally, you need to replace nameLetter = newName.substring(0);
with nameLetter = newName.charAt(0);
as the former returns a string
, the latter a char
.
Upvotes: 4
Reputation: 159754
Enclose character primitives with '
instead of "
private char nameLetter = 'u';
Use charAt
instead of substring
for extracting characters from Strings
nameLetter = newName.charAt(0);
Read: Characters
Upvotes: 1
Reputation: 726539
You need this:
nameLetter = newName.charAt(0);
Of course you must check that newName
's length is at least 1, otherwise there would be an exception:
public void setName(String newName) {
name = newName;
if (newName != null && newName.length() > 0) {
nameLetter = newName.substring(0);
} else {
nameLetter = '-'; // Use some default.
}
}
Upvotes: 7
Reputation: 1477
nameLetter = newName.toCharArray[0];
or you can try
nameLetter = newName.charAt[0];
To know the difference between both this approaches, you can see the answers to this question
Upvotes: 1
Reputation: 8161
You may want to look into the String#charAt(int)
function.
Upvotes: 0