Member Avatar for tehpirate

Hi i want to read words form a text file placed in the same folder as the java file and then hold the information in an array.

so far ive written code to read the text file (i think) im trying to teach my self so if ive done this bit wrong please tell me.

public static void main(String[] args)
{
String testText = IO.readString ("testText.txt");


try
{
FileReader reader = new FileReader(testText);
Scanner in = new Scanner(reader);
out.close();
}//try


catch IOException
{
System.out.println("Error processing file:"
+ exception);
}
}//main

But now i need to hold the words in an array. I was thinking something along the lines of.......

private String[] wordList;
wordList = new String [50];


private void readTestText()
{
String currentWord = scanner.next();
int i = 0;
while (currentWord != null)
{
wordList = currentWord;
currentWord = scanner.next();
i++;
}

What do you think that the right idea and would it work?

The code to read into the array looks reasonable enough, though your while loop should use scanner.hasNext() to determine if more tokens are available before calling next() and you will need to guard against overflowing your array length.

The code at the top to read the text file is never going to compile for you though. There are syntax issues with your catch block declaration and you are calling method on objects that don't exist, like "out.close()". Also have no idea what IO.readString() is supposed to be doing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.