Java 文件未写入输出格式化程序文件

请帮助,我一生都无法弄清楚为什么创建我的输出文件,但没有写入任何内容。我读到一个类似的问题,我不得不关闭输出文件,因为信息被缓冲并且只有在文件关闭时才输出。在阅读那篇文章之前,我已经这样做了,除此之外,我找不到任何其他可以帮助我解决此问题的文章


import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Formatter;

import java.util.Arrays;

public class MyFile {


public static void main(String[] args) {

    try {

        // creating a File instance to reference text file in Java

        File inputFile = new File("C:\\input.txt");


        //creating a Scanner instance to read File in Java

        Scanner scanfile = new Scanner(inputFile);


        //creating a file to output results of program to

        Formatter outputfile = new Formatter("C:\\output.txt");


        //read each line of file using the Scanner instance "scanfile"

        while (scanfile.hasNextLine()) {

            String line = scanfile.nextLine();


            //splitting String "line" into 2 parts at the ":"

            String[] parts = line.split(":");

            String part1 = parts[0];

            String part2 = parts[1];


            //splitting part2 into an array of integers at ","

            String[] lineNumString = part2.split(",");

            int[] lineNums = new int[lineNumString.length];

            for (int i = 0; i < lineNumString.length; i++ ) {

                lineNums[i] = Integer.parseInt(lineNumString[i]);

            }


            /*now that we have the line split into an operator (min, max or avg) and an array of numbers

            we can identify the operator with an if and else if statements, then manipulate the integer array according 

            to the operator*/


            //Outputting max value if operator is max

            if (part1 == "max") {

                String outputText = "The Max of " + Arrays.toString(lineNums) + " is " + maxOfArray(lineNums) + ". \r\n";

                outputfile.format("%s", outputText);


            }


侃侃尔雅
浏览 150回答 2
2回答

潇潇雨雨

使用equals或equalsIgnoreCase不使用==比较字符串&nbsp;if&nbsp;(part1.equals("max"))&nbsp;{

慕斯王

看起来您正确打开/关闭文件。但是,您正在执行直接字符串比较,这意味着您的所有布尔值每次都将返回 false - 从而导致一个空白文件。.equals()在 Java 中比较字符串时使用。例如:if (part1.equals("max")) {do a thing}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java