【问题标题】:First letter of String to Char字符串的第一个字母到 Char
【发布时间】:2013-09-24 14:37:57
【问题描述】:

我拥有的是一个有名字和首字母的学生

所以我有一个班级学生:

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);
}

但我得到错误无法从字符串转换为字符。

我知道我可以用字符串 nameLetter 代替 char,但我想用 char 试试。

【问题讨论】:

  • 使用char时使用单引号,如:char nameLetter = 'u';
  • 这是您的 IDE 会告诉您哪些 String 方法返回 char 的地方(假设您不想阅读 Javadoc)

标签: java string


【解决方案1】:

你需要这个:

nameLetter = newName.charAt(0);

当然要检查newName的长度是否至少为1,否则会出现异常:

public void setName(String newName) {
    name = newName;
    if (newName != null && newName.length() > 0) {
        nameLetter = newName.substring(0);
    } else {
        nameLetter = '-'; // Use some default.
    }
}

【讨论】:

  • 为什么要用newName != null 不带参数是不是不能调用方法? (只是要求不要试图变得聪明)
  • @SvenB 不能在没有参数的情况下调用它,但完全可以传递null 而不是String(不好,但可能)。像这样:myObj.setName(null); 如果没有 null 检查该方法会抛出异常。
  • 如果它提到“u”是字符串文字,“u”是字符,除非你回答。 thx 无论如何,其他答案没有发布您拥有的过滤器。所以无论如何我都赞成,但否则你就是答案
  • @SvenB "如果它提到 "u" 是字符串文字,'u' 是一个字符,请接受你的回答" 我想编译器已经告诉你了 ;-)
【解决方案2】:

"u" 是字符串文字,'u' 是字符。

具体来说,您需要将nameLetter = newName.substring(0); 替换为nameLetter = newName.charAt(0);,因为前者返回string,后者返回char

【讨论】:

    【解决方案3】:
    nameLetter = newName.toCharArray[0];
    

    或者你可以试试

    nameLetter = newName.charAt[0];
    

    要了解这两种方法之间的区别,您可以查看question的答案

    【讨论】:

      【解决方案4】:

      ' 代替" 括起字符基元

      private char nameLetter = 'u'; 
      

      使用charAt 而不是substringStrings 中提取字符

      nameLetter = newName.charAt(0);
      

      阅读:Characters

      【讨论】:

        【解决方案5】:

        试试

        nameLetter = newName.charAt(0);
        

        【讨论】:

          【解决方案6】:

          您可能想查看String#charAt(int) 函数。

          【讨论】:

            猜你喜欢
            • 2020-02-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-10
            • 2018-09-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多