【问题标题】:Trouble writing a method that takes a string and returns an array of chars编写接受字符串并返回字符数组的方法时遇到问题
【发布时间】: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

标签: java arrays string char


【解决方案1】:

在您的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);
}

注意:我知道这是一项任务,必须实现您自己的实现,但为了将来的使用,您可以使用 String 类中的 toCharArray() 方法。用法:color.toCharArray()

【讨论】:

  • 叫我疯了,但要求是创建自己的方法。您可以简单地这样做:public char[] turnStringtoChar(String color) { return color.toCharArray(); } 毕竟,您已经将 String API 用于其他目的。不妨充分利用它。
【解决方案2】:
char[] chars = new char [str.length()];
for (int i=0;i <str.length ();i++) {
    chars [i] = str.charAt (i);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2017-02-09
    • 2021-09-14
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多