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

Modify this lab program so that it writes the result to a file instead of the sc

ID: 3664468 • Letter: M

Question

Modify this lab program so that it writes the result to a file instead of the screen.

import java.util.Scanner;

public class Project1 {

   public static void main(String[] args) {
       // TODO Auto-generated method stub
      
       @SuppressWarnings("resource")
       Scanner S = new Scanner(System.in);
      
       int num1;
       int num2;
       int result;

       num1 = S.nextInt();
       num2 = S.nextInt();
      
       result = num1 * num2;
      
       System.out.printf("Result = %d " , result);

   }

Explanation / Answer

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class Project1 {
   public static void main(String[] args) {
       // TODO Auto-generated method stub

       try {

           @SuppressWarnings("resource")
           Scanner S = new Scanner(System.in);

           File file = new File("result.txt");

           // if file doesnt exists, then create it
           if (!file.exists()) {
               file.createNewFile();
           }

           FileWriter fw = new FileWriter(file.getAbsoluteFile());
           BufferedWriter bw = new BufferedWriter(fw);

           int num1;
           int num2;
           int result;
           num1 = S.nextInt();
           num2 = S.nextInt();

           result = num1 * num2;

           bw.write("Result = " + result);
           bw.close();

           System.out.println("Result Writen to result.txt file ");
       } catch (Exception e) {
           // TODO: handle exception
       }

   }
}

OUTPUT:

3
4
Result Writen to result.txt file

result.txt file

Result = 12

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