The following program is supposed to read two numbers from a file named Input.tx
ID: 3635063 • Letter: T
Question
The following program is supposed to read two numbers from a file named Input.txt and write the sum of the numbers to a file named Output.txt. Assume that the files are in the same file folder where the Criticalthinking.java file is saved.The program below fails to work properly. Thinking about possible reasons for the unexpected results;
1) Determine what is wrong
2) Identify a solution.
3) Change the code below according to your solution.
4) Verify that the input and output are correct.
// Code for your Review
import java.util.*;
public class CriticalThinking
{
public static void main(String[] args)
{
Scanner inFile =
new Scanner(new FileReader("C:\Input.txt"));
int num1, num2;
num1 = inFile.nextInt();
num2 = inFile.nextInt();
outFile.println("Sum = " + (num1 + num2));
outFile.close();
}
}
Explanation / Answer
Hi, So, I copied the code you had on there and started to work on it: So, the problems I noticed were related to the syntax written. Mainly writing the output file. I'm using here FileWrite and BufferedWriter instead of the old way... Another thing I put my input file outside the src folder. In that position I also have my output file. When you're accessing and creating files this way, you can simply write "Input.txt" and "Output.txt" directly. I, also, included all the imports needed for my updated code and for the code to be reviewed. Here's the working code: import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.*; public class CriticalThinking { //Need to add throwsException here public static void main(String[] args) throws IOException { Scanner inFile = new Scanner(new FileReader("Input.txt")); // Had to define outfile here int num1, num2; num1 = inFile.nextInt(); num2 = inFile.nextInt(); // Here's how to write to a file FileWriter fstream = new FileWriter("Output.txt"); BufferedWriter outFile = new BufferedWriter(fstream); outFile.write("Sum = " + (num1 + num2)); outFile.close(); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.