0

I have a text file and i want to read each word into an ArrayList<Dictionary> but I have to leave commas, dashes, dots etc. This is the code so far for this purpose:

Scanner sc2 = null;    
while (sc2.hasNextLine()) {
    Scanner s2 = new Scanner(sc2.nextLine());
    while (s2.hasNext()) {
        String s = s2.next();
        String[] tokens = s.split("\\W+");
        s  = tokens.toString();
        Dictionary.add(s);
    }
}

The problem is that when I execute the printing code :

for (int i = 0; i < Dictionary.size();i++) {
    System.out.println(Dictionary.get(i));
}

I get the following:

[Ljava.lang.String;@ea2f77
[Ljava.lang.String;@ea6137
[Ljava.lang.String;@ea639

Etc. for every word. I belive that the problem is s = tokens.toString(); but i do not know how to fix it. Thank you!

7
  • Oh i forgot to mention that for some reason, eclipse does not let me use Arrays. . Everytime i try to use it, importing the library i get errors. Commented Mar 26, 2016 at 20:02
  • import java.util.Arrays; this is the import statement. Commented Mar 26, 2016 at 20:06
  • Yes i imported but got errors. Anyway thanks! Commented Mar 26, 2016 at 20:08
  • Also note that it looks to me like you could get rid of the split statement and the second scanner by simply iterating over sc2.hasNext() and adding each word to the dictionary. Commented Mar 26, 2016 at 20:08
  • @Maria maybe your eclipse do not have whole source of java :P Commented Mar 26, 2016 at 20:08

3 Answers 3

3

tokens is an array of Strings, and as such its toString() method returns what you see in your output. You need to iterate over each String in tokens and add them to the Dictionary individually, e.g.

for (int i = 0; i < tokens.length; i++) {
    Dictionary.add(tokens[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Maria - great! If that's the case, you should accept the answer by clicking on the check mark over there <---
Yep! Gonna do it in 5 minutes(when it allows me to)
1

if you wanted to avoid for loops; then just use java.util.Arrays--

s = Arrays.toString(s.split("\\W+"));

Comments

0

This is a question that has already been asked, but here's the answer:

String punctutations = ".,:;";//add all the ones you want.
if(punctutations.contains(letter[a])) //If the character at letter[a] contains a punctuation mark

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.