Array declaration
String [] array = new String[20]; // Is this declaration correct?
This declaration is correct for an array of 20 slots of type String (all of them initialized to null
). But you might not need this right away, or not in this form.
You don't need to initialize the variable, especially if you overwrite that initialization by an instruction like: array = ...
.
Getting Input
array = br.readLine(); // Is this the correct way to accept input from keyboard?
Yes, readLine()
is the way to go, but as the doc states, and as you will be told by the compiler, readLine();
does not return an array of String
s but a single String
. You should use a String variable instead:
// initialize a String variable 'line' containing the whole line without the '\n' at the end
String line = br.readLine();
UPDATE: You could also use the Scanner
class instead, that's usually what we do. Then, use sc.nextLine()
for similar results as br.readLine()
, as stated there.
Printing the chars
System.out.println("The "+(i+1)+"character is:" +array[i]+"\n");
//Want to print each and every characters in string along with its position
You can access the character at a given position in a String via the method charAt(int)
. Also, you don't have to deal with complicated C stuff such as looking for the end of the string via '\0'
. You should instead use a proper for
loop, like this:
String line = br.readLine();
for (int i = 0; i < line.length(); i++) {
System.out.println("The "+(i+1)+" character is: " + line.charAt(i) +"\n");
}
An alternate solution would be to use the toCharArray()
method:
String line = br.readLine();
char[] chars = line.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println("The "+(i+1)+" character is: " + chars[i] +"\n");
}