简体   繁体   English

为什么我在USACO的Java代码中得到一个空的输出文件?

[英]Why am I getting an empty output file in my java code for USACO?

This is my code 这是我的代码

import java.util.*;
import java.io.*;
public class palsquare {
    public static void main(String[] args) throws IOException{
        //File file = new File("palsquare.in");
        //Scanner scanner = new Scanner(file);
        BufferedReader in = new BufferedReader(new FileReader("palsquare.in"));
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("palsquare.out")));
        StringTokenizer st = new StringTokenizer(in.readLine());
        int base = Integer.parseInt(st.nextToken());
        for(int i = 1; i < 300; i++){
            String e = Integer.toString(i * i);
            String t = convertFromBaseToBase(e, 10, base);
            if(t.equals(revStr(t))){
                out.println(i + " " + t);
            }
        }

    }
    public static String convertFromBaseToBase(String str, int fromBase, int toBase) {
        return Integer.toString(Integer.parseInt(str, fromBase), toBase);
    }
    public static String revStr(String str){
        String revStr = "";
        for(int i = str.length() - 1; i >= 0; i--)
        {
            revStr = revStr + str.charAt(i);
        }
        return revStr;
    }
}

I am confused as to why my code is not working. 我对为什么我的代码无法正常工作感到困惑。 The trainer for USACO responds to my submission by saying that it returned a blank file but on my computer it works when using Scanner and I dont know how to use this on my computer. USACO的培训师对我的呈件作了回应,说它返回了一个空白文件,但是在我的计算机上,使用扫描仪时它可以工作,我不知道如何在计算机上使用它。 I am only 12 and still learning. 我只有12岁,还在学习。 Thank you in advance. 先感谢您。

The problem here is that there is not flush() operation that pushes the content to the file. 这里的问题是没有将内容推送到文件的flush()操作。 This can be done with .flush() or .close() . 这可以通过.flush().close() Using the nice Closeable interface you can (and this allows to catch exception) : 使用漂亮的Closeable接口,您可以(并且允许捕获异常):

try (BufferedReader in = new BufferedReader(new FileReader("palsquare.in"));
     PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("palsquare.out")))) {

    StringTokenizer st = new StringTokenizer(in.readLine());
    int base = Integer.parseInt(st.nextToken());
    for (int i = 1; i < 300; i++) {
        String e = Integer.toString(i * i);
        String t = convertFromBaseToBase(e, 10, base);
        if (t.equals(revStr(t))) {
            out.println(i + " " + t);
        }
    }

} catch (IOException e) {
    e.printStackTrace();
}

This will automatically close the in/out streams and call the flush() on the output ones 这将自动关闭输入/输出流,并在输出的流上调用flush()

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

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