NoobCoderChick
NoobCoderChick

Reputation: 627

BufferedReader and filling an int array

I have an assignment that I'm having some issues with.

The program uses Buffered Reader and on previous assignments we always had user input on one line and split it using .split("\\s+"). This assignment takes in up to 500 ints all on a separate line until it reaches null.

My problem is parsing the String input into an int array. Usually I have a string array that I set equal to the inputValue.split("\\s+") but the professor said we only need one array (our int array) and I can't figure this out without somehow splitting the input because right now I'm not getting all the input into my int array.

int count = 0;
int intScoresArr[] = new int [500];
//String strArray[];

while((inputValues = BR.readLine()) != null) {
    for(int i = 0; i < inputValues.length(); i++) {
        intScoresArr[i] = Integer.parseInt(strArray[i]);
        count++;
    }
}
average = calcMean(intScoresArr, count);
System.out.println(NF.format(average));

Here is some input and what I'm expecting for output and what I'm actually getting when I loop through and print out the array.

input:
    1
    2
    3
    4
    5

output:
    count: 5
    intScouresArr = 5 0 0 0 0

expected output: 
    count: 5
    intScoresArr = 1 2 3 4 5 

Upvotes: 2

Views: 4415

Answers (1)

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

If you are expecting a single integer per row, you don't need two nested loops; the outer while is enough:

int count = 0;
int intScoresArr[] = new int [500];
String line;

while((line = BR.readLine()) != null) {
    intScoresArr[count] = Integer.parseInt(line.trim());
    count++;
}

Upvotes: 1

Related Questions