Saturday 15 May 2010

java - Trouble writing a method that takes a string and returns an array of chars -



java - Trouble writing a method that takes a string and returns an array of chars -

i'm new java , stuck on code below. don't know how homecoming char array; , if alter string "purple" else, java won't compile code.

public class assigment4 { public static void main(string[] args) { // error if color initialized longer or shorter string. string color = "purple"; char[] = turnstringtochar(color); system.out.println(a); } public static char[] turnstringtochar(string color) { char[] letters = {'p', 'u', 'r', 'p', 'l', 'e'}; (int = 0; < color.length(); i++) { // part stuck. don't know return. letters[i] = color.charat(i); } homecoming letters; } }

can help me?

on turnstringtochar method, need declare letters character array in such way length dependent on length of color variable. if have input longer "purple"; e.g: "yellowwwww"; programme not throw errors.

//this talking char[] letters = new char[color.length()]; (int = 0; < color.length(); i++) { // okay! letters[i] = color.charat(i); }

note: understand assignment , have implement own implementation, future use, can utilize tochararray() method string class. usage: color.tochararray()

java arrays string char

No comments:

Post a Comment