package program.p02;

import java.io.*;
import java.util.*;
import java.lang.*;

public class Dictionary {

    private String[] dictionary;
    private static final int NUMBER_OF_WORDS = 81452;
    private static String FILE_NAME = "dictionarycleaned.txt";

    //no arg constructor???
    public Dictionary() {
        Scanner fin = null;
        //open and test the stream
        try {
            fin = new Scanner(new File(FILE_NAME));
        }//end try
        catch (FileNotFoundException e) {
            System.err.println(e);
            System.exit(1);
        }//end catch
        fin.close();
    }

    public String getRandomWord() {
        //class random?? random number generator
        Random generator = new Random(81452);
        int r = generator.nextInt();

        return dictionary[r];

    }//end getRandomWord()
}//end dictionary class

I am having a bit of trouble with my file IO it is not reading the file apparently and I have no clue why, any one help please?

Java Code

because you didn't code it to read the file. you've just set that he should get his input from that file, but you're not letting your instance of Scanner actually read the input.

okay so here is the edited code and i thought i had finished it for the file IO but im still getting a complie error that says: "java.io.FileNotFoundException: dictionarycleaned.txt (The system cannot find the file specified)
Java Result: 1"

package program.p02;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;

public class Dictionary {

    private String[] dictionary;
    private static final int NUMBER_OF_WORDS = 81452;
    private static String FILE_NAME = "dictionarycleaned.txt";

    //no arg constructor???
    public Dictionary() {
        //create scanner
        Scanner fin = null;
        //open and test the stream
        try {
            fin = new Scanner(new File(FILE_NAME));
        }//end try
        catch (FileNotFoundException e) {
            System.err.println(e);
            System.exit(1);
        }//end catch
        //read data from file.
        while(fin.hasNext()){
            String hiddenWord = fin.next();
            System.out.println(hiddenWord);
        }//end while loop
        //close the file
        fin.close();
    }

    public String getRandomWord() {
        //class random?? random number generator
        Random generator = new Random(81452);
        int r = generator.nextInt();

        return dictionary[r];

    }//end getRandomWord()
}//end dictionary class

That is not a compile error, its a runtime error.
I simply means what it says - it cannot find that file. The file name may be wrong, or it may be in a directory other than the one where Java is looking for it.

This article has been dead for over six months. Start a new discussion instead.