Hi,
I want to read in a word from the user and split the string up into each individual characters, and print the individual characters.
What classes/methods do i need for this ?
Printable View
Hi,
I want to read in a word from the user and split the string up into each individual characters, and print the individual characters.
What classes/methods do i need for this ?
Read the API doc for the String class. It has several methods that will do that.Quote:
split the string up into each individual characters,
Java Platform SE 7
Thanks i have had a go at it.
The program runs as i wanted but it is throwing an exception at the end of it:
Here is the code:Quote:
run:
Enter a word:
liverpool
l
i
v
e
r
p
o
o
l
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at latesttasks.Task21.main(Task21.java:22)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
Code :package latesttasks; // Read in a word as a string and split and print individual characters import java.util.Scanner; public class Task21 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int stringLength; char characters[]; String input; System.out.println("Enter a word: "); input = scan.nextLine(); stringLength = input.length(); characters = input.toCharArray(); for (int i = 0; i <= stringLength; i++) { System.out.println(characters[i]); } } }
--- Update ---
I have just realised the error,
i need to do one less on the loop because as it stands the program would be trying to get one index too many.
Remember the last valid index for an array is the length-1. The posted code goes past that value when it goes to be =