我是 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;
}
}
有人可以帮助我吗?
最佳答案
在您的turnStringtoChar
上方法,您需要声明 letters
字符数组的方式是 length
取决于 color
的长度变量。
因此,如果您的输入长度超过 "purple"
;例如:"yellowwwww"
;
你的程序不会抛出任何错误。
//this is what I am talking about
char[] letters = new char[color.length()];
for (int i = 0; i < color.length(); i++) {
// this is okay!
letters[i] = color.charAt(i);
}
注意:我知道这是一项作业,必须实现您自己的实现,但为了将来使用,您可以使用 toCharArray()
方法来自String
类(class)。用法:color.toCharArray()
关于java - 编写接受字符串并返回字符数组的方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26726449/