Reputation: 63
I need to write those System.out.printlns into a text file, but I have no idea how this could happen so I need some help from someone advanced.
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
And here is the whole code:
import java.io.*;
public class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
try{
do {
EnteredNumbers++;
str = br.readLine();
int num = Integer.parseInt(str);
if (num>0)
{
Positive++;
PositiveSum+=num;
}
else if (num<0)
{
Negative++;
NegativeSum+=num;
}
}
while(!str.equals("0"));
AveragePositive = (double)PositiveSum/(double)Positive;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
catch (java.lang.NumberFormatException ex)
{
System.out.println("Invalid Format!");
}
}
}
I am a beginner and I would love to get some help!
Upvotes: 0
Views: 7704
Reputation: 11
you can use setOut() method for filewrite with System.out.println(); after call setOut() whenever use System.out.println() then the method sop will be print on file or whichever you give in setOut() method
Upvotes: 1
Reputation: 121702
This is 2014. So there is java.nio.file.
Therefore:
final List<String> list = new ArrayList<>();
list.add("first string here");
list.add("other string");
// etc etc
Then:
final Path path = Paths.get("path/to/write/to");
Files.write(path, list, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
And don't use File
.
Upvotes: 0
Reputation: 117569
System.out
is a PrintStream
that writes to the standard output. You need to create a FileOutputStream
and decorates it with PrintStream
(or better FileWriter
with PrintWriter
):
File file = new File("C:/file.txt");
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello World");
pw.close();
Also see:
Upvotes: 4