I am supposed to create a file (done, it's called "factoriales.txt") and print in it the value of 10! (which is 3628800), the thing is, I can't seem to write the value into a file. I already know how to write text, but this wont work.... here's what I have so far. Please help!
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class D09T9e2
{
public static void main(String[] args)
{
try
{
File fac = new File("factoriales.txt");
if (!fac.exists())
{
fac.createNewFile();
}
System.out.println("The file has been created.");
int r = 1;
for (int i = 1; i<=10; i--)
{
r = r * i;
}
FileWriter write = new FileWriter(fac);
write.write(""+r);
write.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Here's how I solved it thanks to everybody in here, I hope you like this simple method:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class D09T9e2
{
public static void main(String[] args)
{
try
{
File fac = new File("factoriales.txt");
if (!fac.exists())
{
fac.createNewFile();
}
System.out.println("\n----------------------------------");
System.out.println("The file has been created.");
System.out.println("------------------------------------");
int r = 1;
FileWriter wr = new FileWriter(fac);
for (int i = 1; i<=10; i++)
{
r = r * i;
wr.write(r+System.getProperty( "line.separator" ));
}
wr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
the reason any way is that
for (int i = 1; i<=10; i--)
runs to infinity since 1 cannot be reduced to 10
it should be
for (int i = 1; i<=10; i++)
and change data type to long as well