Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java character array initializer

I tried to make a program that separates characters. The question is:

"Create a char array and use an array initializer to initialize the array with the characters in the string 'Hi there'. Display the contents of the array using a for-statement. Separate each character in the array with a space".


The program I made:

String ini = "Hi there";
char[] array = new char[ini.length()];

for(int count=0;count<array.length;count++) {
   System.out.print(" "+array[count]);
}

What should I do to fix this problem?

like image 725
Ahmadz Issa Avatar asked Jan 24 '13 10:01

Ahmadz Issa


People also ask

How do you initialize a char array?

You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)

What is an array initializer Java?

Initializing an array in Java involves assigning values to a new array. Java arrays can be initialized during or after declaration. In Java, arrays are used to store data of one single type.

How do you initialize an empty char array in Java?

char ret[] = {};


1 Answers

Here's how you convert a String to a char array:

String str = "someString"; 
char[] charArray = str.toCharArray();

I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray()) and compile errors like the one you have above. You should also familiarize yourself with the documentation, which in this case would be this String documentation.

Also, always post which compile errors you're getting. In this case it was easy to spot, but when it isn't you won't be able to get any answers if you don't include it in the post.

like image 89
keyser Avatar answered Nov 11 '22 07:11

keyser