写日志是程序的常见任务。现在要求在 t1.log, t2.log, t3.log 三个文件间轮流写入日志。也就是说第一次写入
t1.log,第二次写入t2.log,… 第四次仍然写入t1.log,如此反复。
下面的代码模拟了这种轮流写入不同日志文件的逻辑
public class A
{
private static int n = 1;
public static void write(String msg)
{
String filename = "t" + n + ".log";
n = ____________;
System.out.println("write to file: " + filename + " " + msg);
}
}
请填写划线部分缺失的代码.
根据题意,当n=3之后,不允许出现4,重新变成1
所以横线上应填入代码为:
n = n==3?1:n+1;
编写如下代码测试:
private static int n = 3;
public static void write(String msg)
{
String filename = "t" + n + ".log";
n = n==3?1:n+1;
System.out.println("write to file: " + filename + " " + msg);
}
public static void main(String[] args) {
write("test");
write("test");
write("test");
write("test");
write("test");
write("test");
write("test");
}
上述代码,可以打印出
write to file: t3.log test
write to file: t1.log test
write to file: t2.log test
write to file: t3.log test
write to file: t1.log test
write to file: t2.log test
write to file: t3.log test