Write a program that generates 10 random doubles, all between 1 and 11, and writes them to a text file, one number per line. Then write another program that reads the text file and displays all the doubles and their sum accurate to two decimal places.

Answer :

Answer:

WriteDoubleValuesFile.java

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.Random;

public class WriteDoubleValuesFile {

  public static void main(String[] args) throws FileNotFoundException {

      File file = new File("doubleFile");

      PrintWriter pw = new PrintWriter(file);

      double start = 1;

      double end = 11;

      Random random = new Random();

      for(int i=0; i<10; i++){

      double randNum = start + (random.nextDouble() * (end - start));

      pw.write(randNum+"\n");

      }

      System.out.println("File has been geenrated");

     

      pw.flush();

      pw.close();

     

  }

}

ReadDoubleValuesFile.java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Random;

import java.util.Scanner;

public class ReadDoubleValuesFile {

  public static void main(String[] args) throws FileNotFoundException {

      File file = new File("doubleFile");

      Scanner scan = new Scanner(file);

      double sum = 0;

      while(scan.hasNextDouble()){

          double value = scan.nextDouble();

          System.out.println(value);

          sum = sum + value;

      }

      System.out.println("The total is "+sum);

      scan.close();

  }

}

Explanation:

Other Questions