aspose file tools*
The moose likes Beginning Java and the fly likes returning an array of characters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "returning an array of characters" Watch "returning an array of characters" New topic
Author

returning an array of characters

Adam Blais
Greenhorn

Joined: Dec 02, 2004
Posts: 27
I'm trying to write a method that returns the individual characters of a certain string. For example, is String s = "Adam" then c[0] = "A", c[1] = "d" and so on.

I'm not sure how to use a return statement to do this. Here is the method:


[ December 02, 2004: Message edited by: Adam Blais ]
Hentay Duke
Ranch Hand

Joined: Oct 27, 2004
Posts: 198
You need a return statement at the end of your method to return the char array. Also you can eliminate the endloop int variable and just declare your for loop like this.
Adam Blais
Greenhorn

Joined: Dec 02, 2004
Posts: 27
Thanks for the response. My problem is I don't know how to use a return statement to return an array. I thought is was return output[];, but that isn't working. What's the correct command to get this array returned?
[ December 02, 2004: Message edited by: Adam Blais ]
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Your identifier for the char[] is just "output," so all you need is:

return output;

(Note that there's a method in String that already does this. It's toCharArray().)


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Adam Blais
Greenhorn

Joined: Dec 02, 2004
Posts: 27
Thanks Marc, it works fine now.

I'm doing my next exercise, and I need to convert a character array to a string. When I try to use the method in BlueJ and enter the character array with {a, b, c}, it says that it cannot resolve variable a. If I put {"a", "b", "c"}, it says it found a string where a char was expected.
How do I enter in an array?
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1824

{'a', 'b', 'c'}

Use single quotes, not double....


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Adam Blais
Greenhorn

Joined: Dec 02, 2004
Posts: 27
Haha thanks.

Can someone tell me why I'm getting a "possible loss of precision" error in the Math.pow line?

marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Math.pow() returns a double, which you're trying to assign to an int. You'll need to explicitly cast the result to type int...

powerOfTwo[k] = (int)Math.pow(2, k);
[ December 02, 2004: Message edited by: marc weber ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: returning an array of characters