gpt4 book ai didi

java - 方法、字符串、字符有问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:05:48 27 4
gpt4 key购买 nike

我目前正在尝试让我的代码在 hello world 中返回字母“d”,但我不确定代码有什么问题:

 public class StringTest{
public static void main(String [] args){
String test= "Hello World";
world(test);
}

public static String world(String original){
int x= original.charAt(original.length()-1);
return x;
}
}

最佳答案

在Java中,String.charAt(int index)返回一个字符,int不能隐式转换为char

您可以做的是将返回的字符转换为 String 中的 charAt:

public class StringTest{
public static void main(String [] args){
String test= "Hello World";
world(test);
}

public static String world(String original)
{
return Character.toString(original.charAt(original.length()-1));
}

Also, an even easier way:

Create empty String and conacatenate with your char. Automatically this converts char into String since we are adding an element to a String that in itself supports strings of these elements that are char:

    public static String world(String original)
{
return "" + original.charAt(original.length()-1);
}

}

关于java - 方法、字符串、字符有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708842/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com