【发布时间】:2020-04-15 11:00:39
【问题描述】:
我做了一个乘法表。问题是表格没有按应有的顺序排列。
如果我只想将它打印在屏幕上,那么我使用这个System.out.printf(“%4d”)。如何使用BufferedWriter 解决此问题?
而不是这个:
Irj be egy szamot:
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25 `
我想要这个:
Irj be egy szamot:
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25 `
这是我的代码:
public class EgyszerEgy {
public static void main(String[] args) {
int a;
int b;
try {
FileWriter writer = new FileWriter("EgyszerEgy.txt");
BufferedWriter bf = new BufferedWriter(writer);
Scanner tastatur = new Scanner(System.in);
System.out.println("Irj be egy szamot: ");
int szam = tastatur.nextInt();
for (a = 1; a <= szam; ++a) {
for (b = 1; b <= szam; ++b) {
int eredmeny = a * b;
String eredmenyString = String.valueOf(eredmeny);
bf.write(eredmenyString);
bf.write(" ");
}
bf.newLine();
}
bf.flush();
bf.close();
} catch (Exception e) {
}
// Kiolvasas
//String result;
try {
FileReader fr = new FileReader("EgyszerEgy.txt");
BufferedReader br = new BufferedReader(fr);
String result;
while ((result = br.readLine()) != null) {
System.out.println(result);
}
br.close();
} catch (Exception e) {
}
}
}
【问题讨论】:
-
将
System.out.println(result);替换为System.out.printf("%4d", result);。 -
@MaartenBodewes 所以马文比马文做得更好(同一个人)? ??????
-
我认为我发现错误的速度比你快,为时已晚再次:P
-
请注意,尽管 Marvin 的两个建议都有很好的答案,但问题本身非常笨拙且格式错误。 两者都是关于流而不是作家。
标签: java filewriter bufferedwriter