Java:如何将我的数组打印到文本文件?

时间:2021-03-17 09:52:04

标签: java arrays

我一直在尝试让我的程序将数组输出到文本文件时遇到问题。我可以让数组在控制台内打印,但是当尝试打印到我使用 PrintWriter 创建的文本文件时。该文件不包含任何内容。

代码在一个更大的程序中使用的方法中,但我没有包括它,因为这是目前唯一不工作的部分。

try
{
    Scanner user = new Scanner(System.in);          
    System.out.print("Enter a odd number value for n:");
    int n = user.nextInt();
        
    if (n % 2 == 0) {
        System.out.println("Number value must be odd");
    } else {
        Scanner fileName = new Scanner(System.in);
        System.out.print("Enter output file name: ");
        String fileNameChoice = fileName.nextLine();
        String outputfilename = fileNameChoice + ".txt";
        PrintWriter output = new PrintWriter(outputfilename);

        int[][] arrayBox = new int[n][n]; //Initializing array here
        int row = n - 1;
        int column = n / 2;
        arrayBox[row][column] = 1;
        for (int i = 2; i <= n * n; i++) { 
        //Loop to set up the array to the sign of the number inputed 
            if (arrayBox[(row + 1) % n][(column + 1) % n] == 0) {
                row = (row + 1) % n;
                column = (column + 1) % n;
            } else {
                row = (row - 1 + n) % n;
            }

            arrayBox[row][column] = i;
        }

            
        for (int i = arrayBox.length-1; i >= n; i--) { 
        //This took way longer than I care to admit 
        // because I did not flip the greater than and less than signs 
        // while wondering why the array was reversed

            for (int j = 0; j < n; j++) {
                output.print(arrayBox[i][j] + " "); 
                //Prints the array with a tab space between each of the numbers
            }
                        
            output.println();
        }
        output.flush();
        output.close();
    }
}
catch (FileNotFoundException ex)  
{
    System.out.println("There's an error but I'm not sure how you got here.");
    // Couldn't seem to use PrintWriter without adding this the catch lines, 
    // tried to research but I don't think you'll ever get here
}

1 个答案:

答案 0 :(得分:0)

您是否必须使用 PrintWriter?因为我建议您先使用 StringBuilder 来累积整个数组内容,然后使用 FileWriter 写入输出文件。