0

I'm new to Java and stuck on the code below. I don't know how to return the char array; and also if I change the string "purple" to something else, Java won't compile the code.

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

}

Can anyone help me?

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Dee
  • 115
  • 1
  • 1
  • 8
  • 1
    What do you want `letters.length` to be (i.e., how many elements do you want in it)? What is `letters.length` the way you've written it? (And I don't believe that the program doesn't compile if you change the string. It probably throws an exception when you run it. This is _not_ the same as saying it won't compile. It is important to learn the difference.) – ajb Nov 04 '14 at 01:55
  • 2
    Couldn't you just use `toCharArray()`? You could do something like `char[] a = color.toCharArray()` – wns349 Nov 04 '14 at 01:57
  • i could but i have to create my own method to convert the string into an array of chars – Dee Nov 04 '14 at 02:00
  • Look at String's .charAt() method if you can't use toCharArray(). Or is that also not allowed? – MarsAtomic Nov 04 '14 at 02:04
  • 1
    This question has already been answered [here](http://stackoverflow.com/questions/10006165/converting-string-to-character-array-in-java.) – hfontanez Nov 04 '14 at 02:11

2 Answers2

2

On your turnStringtoChar method, you need to declare the letters character array in such a way that its length is dependent on the length of the color variable.
So if you have an input that is longer than "purple"; e.g: "yellowwwww";
your program will not throw any errors.

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

Note: I understand this is an assignment and have to implement your own implementation, but for future use, you can use toCharArray() method from String class. usage: color.toCharArray()

jcera
  • 345
  • 2
  • 11
  • 1
    Call me crazy, but the requirement is to create your own method. You could simply do this: `public char[] turnStringtoChar(String color) { return color.toCharArray(); }` After all, you are already using the String API for other purposes. Might as well take full advantage of it. – hfontanez Nov 04 '14 at 02:21
0
char[] chars = new char [str.length()];
for (int i=0;i <str.length ();i++) {
    chars [i] = str.charAt (i);
}
Steve Siebert
  • 1,874
  • 12
  • 18