Program #1: Work programming exercise 17.3, page 701, Surm integers in you need
ID: 3914960 • Letter: P
Question
Program #1: Work programming exercise 17.3, page 701, Surm integers in you need to create the data file first using writelnt(int) of DataOutputStream. 17.3 (Sum all the integers in a binary data file) Suppose a binary data file named Binary File. Follow the specifications given in the problem statement. Note that Exercise 17 03.dat has been created and its data are created using writeInt Cint) in DataOutputStream. The file contains an unspecified number of integers. Write a program to find the sum of the integers. Please write this Java program as simple as possible and with comments throughout explaining what is happening. Thank youExplanation / Answer
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;
public class Filesumofn {
public static void main(String[] args)
{
writeFile();
readFile();
}
private static void writeFile() {
DataOutputStream output=null;
try {
output = new DataOutputStream(new FileOutputStream("sumofn.txt"));
//Generate 100 random numbers and write to file
Random rn = new Random();
for (int i = 0; i <= 100; i++) {
output.writeInt(rn.nextInt(100));
}
output.flush();
output.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
output.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
private static void readFile() {
DataInputStream input=null;
try {
input = new DataInputStream(new FileInputStream("sumofn.txt"));
int sum = 0;//Initialize sum=0
int number = input.readInt();// Read each number from file
while (true) {
sum += number; //Add number to sum
if (input.available() == 4) {
break;
}
number = input.readInt();
}
System.out.println("Sum = "+sum);
input.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
input.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.