Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

ArrayList help indexing a string

807603Feb 6 2008 — edited Feb 8 2008
Basically for this project, I need the user to input a sentence and then i have to print out the different words with their index.

For example if the user inputs the following:
Hello Hello Hello World World World Hello

The program should output:
Hello 0, 1, 2, 6
World 3,4,5

something in that range well so i attempted this and here is my code:
import java.util.*;
public class Check
{
	public static void main(String[] args)
	{
    	 String word = "";
		 ArrayList <String> diffWord = new ArrayList<String>();
		 ArrayList <Integer> spaces = new ArrayList<Integer>();
	     ArrayList <String> noRepeat = new ArrayList<String>();
		 ArrayList <String> everyThing = new ArrayList<String>();
		 String everything = "";
		 String total = "";
		 String toString = "";
		
		Scanner scan = new Scanner (System.in);
    	String sentence = "";
    	// get the string
    	System.out.println("Please enter a sentence without any capitals or puntuation marks");
    	sentence = scan.next();
    	// get the index for spaces
    	for (int i = 0; i< sentence.length(); i++)
		{
			if(sentence.charAt(i)==(' '))
			{
				spaces.add(i);
			}
		}
		
		// get the different words in Sentence
		for (int i = 0; i< sentence.length(); i++)
		{
			word = sentence.substring(spaces.get(i)+1,spaces.get(i+1));
			diffWord.add(word);
		}
		
		// get position of each word
		for (int i = 0; i < diffWord.size(); i++)
		{
			for (int j = 0; j < diffWord.size(); j++)
			{
				if (diffWord.get(i)!= (noRepeat.get(i)))
					noRepeat.add(diffWord.get(i));
			}
		}
		
		//  get everything in one
		for(int i = 0; i < noRepeat.size(); i++)
		{
			for (int j = 0; j < diffWord.size(); j++)
			{
				if (noRepeat.get(i).equals(diffWord.get(j)))
				{
					everything += (i+" ");
					total = (noRepeat.get(1)+ " "+everything);
					everyThing.add(total);
				}
					
			} 
		}
		// print out everything
		for (int i = 0; i < everyThing.size(); i++)
		{
			toString +=  everyThing.get(i);
		
		}
		System.out.println(toString);
    }
}
it compiles fine but after the sentence is inputted i get the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.RangeCheck(ArrayList.java:546)
    at java.util.ArrayList.get(ArrayList.java:321)
    at DocumentIndex.getDiffWord(DocumentIndex.java:38)
    at IndexMaker.main(IndexMaker.java:17)

Process completed.
Can someone PLEASE help me??? I'v been stuck on the same project for the past 4 hours and none of my friends seem to understand what to do...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 7 2008
Added on Feb 6 2008
10 comments
203 views