Write a main() function in which the program will request the user to enter a fi
ID: 639610 • Letter: W
Question
Write a main() function in which the program will request the user to enter a file name then attempt to open the file with that name. If the file does not exist ,write an error message. If the file exists but doesn't contain data write and error message. If the the file doesn't exist and contains data then your program calls a function int ElementNum(ifstream &x) {...} inside the method the code should read all integers and aslo displaythe total number of integers in the file. use while loop with a eof (end of file) condition (use a .dat file and write any integer data to test)
Explanation / Answer
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
// The buffering makes the program more than 20 times faster.
public class SumFile {
public static void main(String[] a) throws IOException {
sumfile("file.dat");
}
static void sumfile(String filename) throws IOException {
Reader r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
double sum = 0;
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER)
sum += stok.nval;
else
System.out.println("Nonnumber: " + stok.sval);
stok.nextToken();
}
System.out.println("The file sum is " + sum);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.