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 ?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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.split the string up into each individual characters,
Java Platform SE 7
If you don't understand my answer, don't ignore it, ask a question.
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: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)
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 =
If you don't understand my answer, don't ignore it, ask a question.