Reputation: 29
Hi guys I seem to have trouble with a program
A sample input can be as follows:
3 1 2 3
0 1 12
-12
14 1 2 3
5 1 2 3 4 5 6
4 10 20 30 40
Sample output has to be : The average of the values on line 1 is 2.0
*** Error (line 2): Line is empty - average can't be taken
*** Error (line 3): Header value of 0 - average can't be taken
The average of the values on line 4 is 12.0
*** Error (line 5): Corrupt line - negative header value
*** Error (line 6): Corrupt line - fewer values than header
*** Error (line 7): Corrupt line - extra values on line
The average of the values on line 8 is 25.0
There were 3 valid lines of data
There were 5 corrupt lines of data
This is what I have so far :
public class DataChecker
public static void main(String[] args) throws IOException {
File myFile = new File("numbers.text");
Scanner scanner = new Scanner(myFile);
int count=0,count2=0,sum=0;
int[] val = new int[50];
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
count++;
while(lineScanner.hasNextInt()){
lineScanner.nextInt();
count2++;
}
if(lineScanner.hasNextInt())
val[count2] = lineScanner.nextInt();
for(int i =0;i<count2;i++) {
sum += val[i];
sum = (sum/count2);
System.out.println(sum);
}
System.out.println("There are " + count2 + " numbers on line " + count);
lineScanner.close();
count2=0;
}
scanner.close();
}
I appreciate any help.
Upvotes: 2
Views: 134
Reputation: 521269
You are not taking a proper tally of the numbers on each line. The algorithm should be to read in a line, tokenize it using a scanner, then consume integers until there are no more. Keep track of both the total sum and the number of ints seen, then take the quotient of these two sums to get the average.
// your initialization code
int numLines = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
numLines++;
int count = 0;
int total = 0;
while (lineScanner.hasNextInt()) {
total += lineScanner.nextInt();
++count;
}
if (count == 0) {
System.out.println("Line " + numLines + " has no numbers.");
continue;
}
double avg = 1.0d * total / count;
System.out.println("The average of the values on line " + numLines + " is " + avg);
lineScanner.close();
}
Upvotes: 3