gpt4 book ai didi

Java 将模式写入文件

转载 作者:行者123 更新时间:2023-11-29 04:39:02 25 4
gpt4 key购买 nike

我的一个程序遇到了一些问题,希望 SO 社区能提供帮助。所以我有这个程序要求用户输入一个数字。在他们输入数字后,程序将显示一系列 X。举个例子,假设用户输入 8。程序将在一行和一列中显示 8 个 x,如下所示:

XXXXXXXX                                                                           
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX

我遇到的问题是我需要将其写入文件。我只能让它打印一行 X。因此,如果有人能告诉我如何制作上面的图表将打印到 squares.txt,那就太棒了。

import java.util.Scanner;
import java.io.*;
public class squareOutput {

public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer between 1 and 15");
int number = keyboard.nextInt();
while (number > 15 || number <1){
System.out.println("Sorry, thats a invalid number");
number = keyboard.nextInt();
}
keyboard.nextLine();
keyboard.close();
FileWriter fwriter = new FileWriter("square.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);

for (int r = 0; r < number; r++)
{


for (int c = 0; c < number; c++)
{
System.out.print("X");

outputFile.print("X");
}
outputFile.println("");
System.out.println("");



outputFile.close();
}
}

最佳答案

outputFile.close(); 需要在 for 循环之外。您只想在所有写入完成后才关闭文件。

import java.util.Scanner;
import java.io.*;
public class squareOutput {

public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer between 1 and 15");
int number = keyboard.nextInt();
while (number > 15 || number <1){
System.out.println("Sorry, thats a invalid number");
number = keyboard.nextInt();
}
keyboard.nextLine();
keyboard.close();
FileWriter fwriter = new FileWriter("square.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);

for (int r = 0; r < number; r++)
{


for (int c = 0; c < number; c++)
{
System.out.print("X");

outputFile.print("X");
}
outputFile.println("");
System.out.println("");



// outputFile.close(); <-- NOT HERE
}
outputFile.close(); // <-- HERE
}
}

关于Java 将模式写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40011248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com