【发布时间】:2014-12-30 19:54:58
【问题描述】:
我是 Java 新手,坚持使用下面的代码。我不知道如何返回 char 数组;而且如果我将字符串"purple" 更改为其他内容,Java 将不会编译代码。
public class Assigment4 {
public static void main(String[] args) {
// I get an error if color is initialized with a longer or shorter string.
String color = "purple";
char[] a = turnStringtoChar(color);
System.out.println(a);
}
public static char[] turnStringtoChar(String color) {
char[] letters = {'p', 'u', 'r', 'p', 'l', 'e'};
for (int i = 0; i < color.length(); i++) {
// This is the part where I am stuck. I don't know what to return.
letters[i] = color.charAt(i);
}
return letters;
}
}
谁能帮帮我?
【问题讨论】:
-
你想要
letters.length是什么(即你想要多少元素)?你写的letters.length是什么? (而且我不相信如果您更改字符串,程序不会编译。运行它时它可能会抛出异常。这 not 与说它不会编译相同。了解差异很重要。) -
你不能用
toCharArray()吗?你可以做类似char[] a = color.toCharArray() -
我可以,但我必须创建自己的方法来将字符串转换为字符数组
-
如果不能使用 toCharArray(),请查看 String 的 .charAt() 方法。或者这也是不允许的?
-
这个问题已经回答here