In: Computer Science
Java Programming:
In the program shown below, I want to print the result in the output file. The main static method calls a method, displaySum which adds two integers and prints the result (sum). The problem is that I am not able to use "outputFile.print()" inside displaySum to print the content as the output file. I also want to display the content of two other methods, but I am facing this difficulty.
** DisplayOutput.java **
import java.io.*;
public class DisplayOutput
{
public static void main(String[] args) throws
IOException
{
FileWriter fw = new
FileWriter("output.txt");
PrintWriter outputFile = new
PrintWriter(fw);
outputFile.println("Suppose two
inetegers are 2 and 3.");
outputFile.println("Display the sum
of two inetegers (2 and 3).");
displaySum(2,3);
outputFile.close();
}
private static void displaySum(int n1, int n2)
{
int sum = n1 + n2;
outputFile.print("Sum of two integers (2 and 3)
is: " + sum); // Error: outputFile cannot be
resolved
}
}
This can be solved in 2 ways, I have provided both solutions:
Solution 1)
Pass the PrintWriter outputFile, as an argument to method displaySum
---------DisplayOutput.java---------------------
import java.io.*;
public class DisplayOutput
{
public static void main(String[] args) throws IOException
{
FileWriter fw = new FileWriter("output.txt");
PrintWriter outputFile = new PrintWriter(fw);
outputFile.println("Suppose two inetegers are 2 and 3.");
outputFile.println("Display the sum of two inetegers (2 and
3).");
displaySum(2,3,
outputFile); //Pass the outpuFile argument to displaySum
Method
outputFile.close();
}
private static void
displaySum(int n1, int n2, PrintWriter outputFile)
{
int sum = n1 + n2;
outputFile.print("Sum of two integers (2 and 3) is: " + sum);
}
}

---------------------------------------------------------------------------------
Solution 2)
Declare the FileWriter and PrintWriter objects outside main, so they can be accessed in all methods
---------DisplayOutput.java---------------------
import java.io.*;
public class DisplayOutput
{
static
FileWriter fw ;//Declare file and print objects outside, so it can
be accessed in all methods
static
PrintWriter outputFile;
public static void main(String[] args) throws
IOException
{
fw = new
FileWriter("output.txt");
outputFile = new
PrintWriter(fw);
outputFile.println("Suppose two
inetegers are 2 and 3.");
outputFile.println("Display the sum
of two inetegers (2 and 3).");
displaySum(2,3); //Pass the
outpuFile argument to displaySum Method
outputFile.close();
}
private static void displaySum(int n1, int n2)
{
int sum = n1 + n2;
outputFile.print("Sum of two
integers (2 and 3) is: " + sum);
}
}

-------------------Output---------------------

-----------------------------------------
I hope this helps you,
Please rate this answer if it helped you,
Thanks for the opportunity