有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java While循环覆盖其他输入

每当我向这个循环中输入内容时,不管有多少,它都只会将我的最终输入写入文件 以下是代码:

import java.util.Scanner;
import java.io.IOException;
import java.io.*;

class lista {
    public static void main(String[] args) throws IOException {
        Scanner n = new Scanner(System.in);
        int x = 0;
        File productList = new File("productList.txt");
        FileWriter fr = new FileWriter("productList.txt", true);

        /// While Loop Start

        while (x == 0) {
            System.out.println("Enter the product:");
            String product = n.nextLine();
            System.out.println("");
            System.out.println("Enter the price:");
            String price = n.nextLine();
            System.out.println("");
            System.out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
            String type = n.nextLine();
            System.out.println("");
            System.out.println(product + " - " + "$" + price + " (" + type + ")" + "\n\n");
            try {
                fr.write((product + " - " + "$" + price + " (" + type + ")" + "\n\n"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Type \"0\" if you would like to stop, type \"1\" if you would like to continue.");
            int y = n.nextInt();
            n.nextLine();
            if (y == 1) {
                x = 0;
            } else {
                x = 1;
                fr.close();
            }
        }
        /// While Loop Ends

    }
}

我可以输入这样的信息, 1,1,1,1 2,2,2,1 3,3,3,0 ,它只会打印:

3 - $3 (3)

谢谢


共 (1) 个答案

  1. # 1 楼答案

    这可能是Trouble with filewriter overwriting files instead of appending to the end的重复。 不过,您似乎已经找到了解决方案(创建FileWriter时的true参数)。这应该附加到文件中,而不是覆盖它。如果这不起作用,那么您可能会遇到文件或操作系统的问题。在任何情况下,您的代码都不是根本错误,应该可以正常工作

    关于代码本身的可读性和易用性的一些建议(只是一些小细节)

    Scanner in = new Scanner(System.in);
    PrintStream out = System.out;
    
    try (FileWriter writer = new FileWriter("productList.txt", true)) {
        INPUT_LOOP:
        while (true) {
            out.println("Enter the product:");
            String product = in.nextLine();
            out.println();
    
            out.println("Enter the price:");
            String price = in.nextLine();
            out.println();
    
            out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
            String type = in.nextLine();
            out.println();
    
            String entry = product + " - " + "$" + price + " (" + type + ")" + "\n\n";
            out.println(entry);
            writer.append(entry);
    
            out.println("Type \"exit\" if you would like to stop, any other input will continue.");
            if (in.nextLine().trim().toLowerCase().equals("exit")) {
                break INPUT_LOOP;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }