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

JAVA PROGRAM Write a program named WriteRandom.java that creates a file named “r

ID: 3816636 • Letter: J

Question

JAVA PROGRAM

Write a program named WriteRandom.java that creates a file named “randy.txt”. The program should first prompt for the number of lines that are to be written to this file. This input value should be between 5 and 15. Then you must use a loop to output that number of lines to the file.   Each line written should consist of a random number between 1 and 50. After the lines have been written, the file should be closed and the following should be displayed on the console:

## lines, each containing a random number between 1 and 50, have been written to the file .

Where “##” is replaced with the actual number of lines your program wrote.

Explanation / Answer

WriteLinesToRandy.java


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class WriteLinesToRandy {

   public static void main(String[] args) throws IOException {
       int nos, randNum;
       Random r = new Random();
       // Scanner object is used to get the inputs entered by the user
       Scanner sc = new Scanner(System.in);

       // validate the user input
       while (true) {
           // getting the number entered by the user
           System.out.print(" How many no of lines has to be written to the file :");
           nos = sc.nextInt();
           if (nos < 5 || nos > 15) {
               System.out.println("Invalid.Must be between 5 and 15(inclusive)");
               continue;
           } else
               break;
       }

       BufferedWriter bw=new BufferedWriter(new FileWriter("D: andy.txt"));
      
       try {

           for (int i = 1; i <= nos; i++) {
               randNum = r.nextInt(50) + 1;

               // Writing RandomNumbers to the output file
               bw.write(randNum + " ");

           }

       } catch (Exception e) {
           e.printStackTrace();
       }
       bw.close();

       System.out.println(nos+ " lines, each containing a random number between 1 and 50, have been written to the file .");

   }

}

______________________

Output console:
How many no of lines has to be written to the file :26
Invalid.Must be between 5 and 15(inclusive)

How many no of lines has to be written to the file :3
Invalid.Must be between 5 and 15(inclusive)

How many no of lines has to be written to the file :14
14 lines, each containing a random number between 1 and 50, have been written to the file .

______________________

randy.txt (We can find this file under D Drive.As we specified the path of the output file as D: andy.txt)

9
41
20
45
25
38
19
18
44
49
32
37
8
3

__________________