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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.