View Full Version : java help: reading data from file
dbbolton
October 28th, 2007, 03:50 PM
i need a little help with a java programming assignment. i have to write a program that reads a file such as:
Smith 85 83 77 91 76
Jones 87 90 88 91 94
and outputs something like:
Student Test1 Test2 Test3 Test4 Test5 Average Grade
Smith 85 83 77 91 76 82.4 B
...
i need help getting the program to read the data from the file using loops. could someone help me with this?
Ramses de Norre
October 28th, 2007, 04:07 PM
Use a Scanner, if the file is named text_file.txt you do like this:
Scanner scanner=new Scanner(new FileInputStream(new File("text_file.txt")));
And then you can read out the file with the methods next{,Int,Line}, use as needed and read up on scanner here (http://java.sun.com/javase/6/docs/api/java/util/Scanner.html).
dbbolton
October 28th, 2007, 04:23 PM
thanks!
how do i loop it to read the whole file and get the data for each student?
\Oo._.oO/
October 28th, 2007, 05:09 PM
Assuming that the file contains one line for each student and the number of students is not defined you need something like this:
// read the whole file one line at a time
while(scanner.hasNextLine()) {
// read students name
for (int i=0; i<5; i++) {
// read the i:th exam score
}
}
pmasiar
October 29th, 2007, 09:16 AM
Here is why I prefer Python over java: I can open, read and parse file in 3 lines of code without consulting manual
for line in open('path/to/input/file'):
parts = line.split(' ')
name, grades = parts[0], parts[1:]
# calculations, output etc
Ramses de Norre
October 29th, 2007, 11:38 AM
Here is why I prefer Python over java: I can open, read and parse file in 3 lines of code without consulting manual
for line in open('path/to/input/file'):
parts = line.split(' ')
name, grades = parts[0], parts[1:]
# calculations, output etc
He's asking about something specifically in java, python is no option here...
dbbolton
October 29th, 2007, 12:54 PM
i'm sure that my CS prof would be amused if i turned in a python program for my java assignment
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.