1

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.

Sven van den Boogaart
  • 11,134
  • 17
  • 82
  • 155

6 Answers6

7

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.
    }
}
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • Why do you use newName != null isn't it impossible to call the method without a parameter? (just asking not trying to be smart) – Sven van den Boogaart Sep 19 '13 at 13:36
  • @SvenB One cannot call it without a parameter, but it is perfectly possible to pass `null` instead of a `String` (not good, but possible). Like this: `myObj.setName(null);` Without a `null` check the method would throw an exception. – Sergey Kalinichenko Sep 19 '13 at 13:38
  • Would except you answer if it mentioned "u" is a string literal, 'u' a char. thx anyway the other answer didnt post the filter you had. so i upvoted it anyway but else you were the answer – Sven van den Boogaart Sep 19 '13 at 15:04
  • @SvenB "accept you answer if it mentioned "u" is a string literal, 'u' a char" I thought the compiler has already told you that ;-) – Sergey Kalinichenko Sep 19 '13 at 15:49
4

"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.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
1

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

Reimeus
  • 155,977
  • 14
  • 207
  • 269
1
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

Community
  • 1
  • 1
Farax
  • 1,419
  • 2
  • 20
  • 36
0

try

nameLetter = newName.charAt(0);
upog
  • 4,565
  • 7
  • 35
  • 70
0

You may want to look into the String#charAt(int) function.

BambooleanLogic
  • 6,778
  • 3
  • 32
  • 52