繁体   English   中英

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

[英]Java: How to print my array to a text file?

我在尝试将我的程序将 output 数组转换为文本文件时遇到了麻烦。 我可以让数组在控制台内打印,但是当尝试打印到我使用 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
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM