我需要将那些System.out.printlns写入文本文件,但我不知道这是怎么发生的,所以我需要一些先进的人帮助。
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+ "!");
以下是整个代码:
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!");
}
}
}
我是初学者,我很乐意得到一些帮助!
答案 0 :(得分:3)
System.out
是写入标准输出的PrintStream
。您需要创建一个FileOutputStream
并使用PrintStream
(或更好FileWriter
PrintWriter
)来装饰它:
File file = new File("C:/file.txt");
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello World");
pw.close();
另见:
答案 1 :(得分:0)
这是2014年。所以有java.nio.file。
因此:
final List<String> list = new ArrayList<>();
list.add("first string here");
list.add("other string");
// etc etc
然后:
final Path path = Paths.get("path/to/write/to");
Files.write(path, list, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
答案 2 :(得分:0)
你可以使用setOut()方法将filewrite与System.out.println();在调用setOut()之后每当使用System.out.println()时,方法sop将打印在文件上或者你在setOut()方法中给出的那个