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,833
  • 21
  • 86
  • 169

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
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 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
  • 231,907
  • 34
  • 361
  • 483
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
  • 158,255
  • 15
  • 216
  • 276
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,447
  • 3
  • 20
  • 37
0

try

nameLetter = newName.charAt(0);
upog
  • 4,965
  • 8
  • 42
  • 81
0

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

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56