Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Write code that does the following: Opens a file named numbers.txt, uses a

ID: 3713597 • Letter: J

Question

Java

Write code that does the following: Opens a file named numbers.txt, uses a loop to write the odd numbers from 1 through 200 to the file and then close the file Write the code that does the following: Open the file numbers.txt created in the question 4. Read all of the numbers from the file Count how many numbers in the file (store in the variable count) add all these numbers (store in the variable sum) close the file numbers.txt display the message: There are count numbers Sum of them is: sum

Explanation / Answer

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class Driver {

public static void main(String[] args){

BufferedReader b;

try {

b = new BufferedReader(new FileReader("data.txt"));

BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"));

for(int i = 1; i < 200; i = i + 2)

bw.write(String.valueOf(i) + " ");

bw.close();

String line = "";

int count = 0, sum = 0;

while((line = b.readLine()) != null) {

int number = Integer.parseInt(line);

count++;

sum += number;

}

System.out.println("There are " + count + " numbers");

System.out.println("Sum of them is: " + sum);

b.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

**Comment for any further queries.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote