1 Replies - 203 Views - Last Post: 02 April 2013 - 11:05 AM Rate Topic: -----

#1 sinder3lla48  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 15-February 13

Splitting a Word

Posted 02 April 2013 - 10:57 AM

I am currently being asked to create a program that prompts the user to enter a single word, and then the prints the word out with each letter on a separate line. It must work for a word of any length and use a simple loop with string functions to extract the letters. I have this so far, but it doesn't do anything after you enter the word.

import java.util.Scanner;

public class WordSplit 
{
	public static void main(String [] args)
	{
		String inputString = "";
		Scanner in = new Scanner(System.in);
	
		System.out.print("Enter a word: ");
		char[] characterArray = inputString.toCharArray();
		inputString = in.nextLine();
	for(int i=0; i<characterArray.length; i++)
	{
		char character = characterArray[i];
	    System.out.println(character);
	}
    }
}


Is there any way to do this without arrays? I know how to use them because of a previous class but we haven't actually learned about them in this one.

Is This A Good Question/Topic? 0
  • +

Replies To: Splitting a Word

#2 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7561
  • View blog
  • Posts: 12,678
  • Joined: 19-March 11

Re: Splitting a Word

Posted 02 April 2013 - 11:05 AM

        char[] characterArray = inputString.toCharArray();
        inputString = in.nextLine();



These two lines are in the wrong order. You want to get the input string and then turn it into a char array.

Quote

Is there any way to do this without arrays? I know how to use them because of a previous class but we haven't actually learned about them in this one.


Use the charAt method to get the char at a given index. The length method will tell you how many chars there are to work with, and of course a loop from 0 to length-1 will iterate through the characters one at a time.

Of course, you're still using an array, but the array is under the hood, in the String class, so you don't need to think about it. (but if you've played with arrays it should feel very familiar)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1