0

I want to fill an array with names. The array should be filled depending on what gender the character is.

public void fillNameArray() throws IOException {
    Character character = new Character(); //Declare and initialise character object

    if(character.getGender() == "F"){ 
        List<String> lines = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("femaleNames.txt"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } finally {
            reader.close();
        }
        String[] array = (String[]) lines.toArray();
    }
    else{
        List<String> lines = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("maleNames.txt"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } finally {
            reader.close();
        }
        String[] array = (String[]) lines.toArray();
    }

}
Auguste
  • 2,007
  • 2
  • 17
  • 25
  • 3
    and the question is? – Jordi Castilla May 31 '16 at 14:46
  • What is the Question you are trying to ask here?? – Raj K May 31 '16 at 14:50
  • 1
    The purpose of StackOverflow is not writing your code for you (if that's what you were hoping for). On the other hand, if some kind of exception is being thrown, or you are getting an output that is not what you expected, please include this information in your original question so we can immediately zero in on the issue. – Monkeygrinder May 31 '16 at 15:00
  • 1
    I'd also be cautious about using `Character` as the name for your class, given that it's also the name of the major Java class corresponding to the primitive type `char`. I imagine there are plenty of other class names you could use that are adequately descriptive that would also avoid any confusion. – Monkeygrinder May 31 '16 at 15:27

1 Answers1

0

The problem is in the following line:

String[] array = (String[]) lines.toArray();

Write instead:

String[] array = lines.toArray(new String[lines.size()]);

See post as example.

Please can you also move the read code on a own method? So less code duplication.

public List<String> readNames(String file) {
    List<String> lines = new ArrayList<String>();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(file));
        String line = null;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
    } finally {
        reader.close();
    }
    return lines;
}
Community
  • 1
  • 1
wake-0
  • 3,918
  • 5
  • 28
  • 45