-4

I'm working on a task where the results of a method will print into an existing text file. How do I get this method to print into the file, instead of the main when getDivisors() is called in the main? In the main method, I also ask the user for input of a name and it will create a .txt file with numbers inside the file.

public static void getDivisors(double n) 
{ 
    for (int i=1;i<=n;i++) 
        if (n%i==0) 
            System.out.println(i+" ");
            System.out.println("The divisors for " + n + " are" + " listed above"); 
            System.out.println(" ");
} 
Trainer Red
  • 7
  • 1
  • 4

1 Answers1

0

You can use FileWriter like so:

try {
    FileWriter myWriter = new FileWriter("filename.txt", true);
    for (int i = 1; i <= n; i++)
        if (n % i == 0){
            myWriter.write(i + " ");
            myWriter.write("The divisors for " + n + " are" + " listed above");
            myWriter.write(" ");
        }
    myWriter.close();
} catch (IOException) {
    e.printStackTrace();
}

We can turn on append mode by specifying true as the second argument in the constructor. This will append the text to the file, rather than deleting everything and rewriting.

For good practice, we will catch an IOException, since that's the only error that a FileWriter throws.

Spectric
  • 30,714
  • 6
  • 20
  • 43