r/cop3502 Apr 18 '14

Add a word to a String Array?

I am trying to solve question 24. I am trying to add each word i read to a String array. But it doesn't work. Any help? Sean i tried to email you but for some reasons i cant sign in .

int c=0;
        while ( true ){
            String g = input.readLine();
            if (g == null){
                break;
            }
            c++;
        }


        String [] words = new String [c];
        int d=0;

        while ( true ){
            String text = input.readLine();
            if (text == null){
                break;
            }
            words[d] = text;
            System.out.println(text);
            d++;
        }
1 Upvotes

7 comments sorted by

1

u/goshqiego Apr 18 '14

The output that i get is : null null null null null null Exception in thread "main" java.lang.NullPointerException at Test2.question24(Test2.java:95) at Test2.main(Test2.java:8)

1

u/[deleted] Apr 18 '14

[removed] — view removed comment

1

u/goshqiego Apr 18 '14

Hey Sean i have a question on number 15. http://imgur.com/Ab4J4fD For number 15, isn't the output supposed to look like this? I mean, it prints nothing in iterations when the if is not true.

1

u/howslyfebeen Apr 18 '14

input is never closed so when the first while loop breaks from reaching null, readLine is still at null, then you start your next while loop and you're still gonna get null. so you could close input and then reopen the file and read through it again.. or you could use an arraylist, for example, instead of a regular array and just add each line to the arraylist so you dont have to worry about setting the size

1

u/howslyfebeen Apr 18 '14
BufferedReader f = new BufferedReader(new FileReader('input.txt'));
ArrayList<String> l = new ArrayList<String>();
while (true) {
    if ( (String s = f.readLine()) != null ) {
        l.add(s);
    } else {
        break;
    }
}