簡體   English   中英

如何將其寫入 Java 中的文本文件?

[英]How can I write it to a text file in Java?

編輯:我在 PrintWriter 的幫助下修復了它。

所以,我有這個程序,或者程序中的這個循環。 它從文件中讀取數據,然后如果 ok = true 則打印 YES,如果 ok = false 則打印 NO。 output 到控制台工作,打印:

NO
YES

但我需要它以相同的方式將其打印到文本文件中。 嘗試使用 BufferedReader,但它只打印

YES
for (int j = 0; j < m; j++)
{
    str = s.nextLine();
    String[] pair = str.split("\\s+");
    int x = Integer.parseInt(pair[0]);
    int y = Integer.parseInt(pair[1]);
    System.out.printf("Switching cards: %d %d\n",x,y);
    x--;
    y--;
    Pair tempPair = P[x];
    P[x] = P[y];
    P[y] = tempPair;
    int p = -infty;
    boolean ok = true;
    for (int i = 0; i < n; i++)
    {
        if (P[i].first >= p)
        {
                p = P[i].first;
        }
        else if (P[i].second >= p)
        {
                p = P[i].second;
        }
        else
        {
                ok = false;
                break;
        }
    }
   
    System.out.println(ok ? "YES\n" : "NO\n");
}

我修改你的代碼試試這個。

BufferedWriter output = null;
        try {    
        File file = new File("example.txt");
        output = new BufferedWriter(new FileWriter(file));
        for (int j = 0; j < m; j++) {
                str = s.nextLine();
                String[] pair = str.split("\\s+");
                int x = Integer.parseInt(pair[0]);
                int y = Integer.parseInt(pair[1]);
                System.out.printf("Switching cards: %d %d\n", x, y);
                x--;
                y--;
                Pair tempPair = P[x];
                P[x] = P[y];
                P[y] = tempPair;
                int p = -infty;
                boolean ok = true;
                for (int i = 0; i < n; i++) {
                    if (P[i].first >= p) {
                        p = P[i].first;
                    } else if (P[i].second >= p) {
                        p = P[i].second;
                    } else {
                        ok = false;
                        break;
                    }
                }
            
                System.out.println(ok ? "YES\n" : "NO\n");
                output.write(ok ? "YES\n" : "NO\n");
            }
        } 
    catch ( IOException e ) {
                    e.printStackTrace();
                } 
    finally {
                  if ( output != null ) {
                    output.close();
                  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM