将文本文件读入数组并执行不同的任务

时间:2017-12-11 03:38:22

标签: java

我有一个包含图书信息的文件。我需要将文件读入数组然后提供菜单。当我运行代码并选择选项1时,文本文件中的数据将被删除。为什么会这样?当选择选项1时,我需要用户能够选择书籍,书籍数量并向他们显示价格

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

public class BookProgram {

    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) throws FileNotFoundException {
        Scanner fileInput = new Scanner(new File("src/BookData.txt"));
        PrintWriter output = new PrintWriter("src/BookData.txt");
        String newID = "";
        String title = "";
        String newPrice = "";

        ArrayList<String> prices = new ArrayList<>();
        ArrayList<String> IDs = new ArrayList<>();

        while (fileInput.hasNextLine()) {
            prices.add(fileInput.next());
            String line = fileInput.nextLine();
            String[] price = line.split(" ");
            prices.add(price[0]);
            IDs.add(price[1]);
        }

        // display menu
        display();
        int userChoice = input.nextInt();
        while (fileInput.hasNextLine()) {
            System.out.println(fileInput.nextLine());
        }

        if (userChoice == 1) {
            System.out.println("Enter the Book ID that you wish to buy: ");
            int bookID = input.nextInt();
            System.out.println("How many of those books do you want to buy?: ");
            int numOfBooks = input.nextInt();
            System.out.println("Price: " + numOfBooks);
        }

        if (userChoice == 2) {
            addBook();
            output.println(newID + " " + title + " " + newPrice); // save to the
                                                                    // file
        }
    }

    // method to display menu
    public static void display() {
        System.out.println("1) Purchase Menu");
        System.out.println("2) Add Book to Inventory");
        System.out.println("3) Remove Book from Inventory");
        System.out.println("4) Quit");
        System.out.println("Enter your choice: ");
    }

    // method to display all the info
    public static void purchaseMenu() {

    }

    // method to add to the text file
    public static void addBook() {
        System.out.println("Enter the ID: ");
        String newID = input.nextLine();
        System.out.println("Enter the title: ");
        String title = input.nextLine();
        System.out.println("Enter the price: ");
        String newPrice = input.nextLine();
    }
}

1 个答案:

答案 0 :(得分:0)

//您可以使用此代码将文本读入数组。然后在数组元素上按照您的意愿执行操作。

BufferedReader abc = new BufferedReader(new FileReader(yourfilehere));
List<String> lines = new ArrayList<String>();

while((String line = abc.readLine()) != null) {
    lines.add(line);
    System.out.println(data);
}
abc.close();

//转换为字符串

String[] data = lines.toArray(new String[]{});
相关问题