Java ArrayList仅从分隔符文件复制最后一个值
我有一个库程序,它将值添加到数组列表中,并将列表写入分隔文件。填充数组列表时,它只复制最后的值。以下是我现在掌握的代码:Java ArrayList仅从分隔符文件复制最后一个值,java,javafx,arraylist,Java,Javafx,Arraylist,我有一个库程序,它将值添加到数组列表中,并将列表写入分隔文件。填充数组列表时,它只复制最后的值。以下是我现在掌握的代码: // LibraryGUI.java file import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import j
// LibraryGUI.java file
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.util.Optional;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
public class LibraryGUI extends Application {
private Library library = new Library(this);
private static Button btAddItem = new Button("Add");
private static Button btCheckOut = new Button("Check Out");
private static Button btCheckIn = new Button("Check In");
private static Button btDelete = new Button("Delete");
private ListView<String> list;
@Override
public void start(Stage primaryStage) throws Exception {
HBox buttonPanel = new HBox();
buttonPanel.getChildren().addAll(btAddItem, btCheckOut, btCheckIn, btDelete);
buttonPanel.setAlignment(Pos.CENTER);
buttonPanel.setSpacing(17);
list = new ListView<String>();
list.setEditable(true);
ObservableList<String> allItems = FXCollections.observableArrayList(library.listAllItems());
list.setItems(allItems);
allItems.addListener((ListChangeListener<Object>) change -> {
System.out.println("List View Changed");
});
BorderPane bPane = new BorderPane();
BorderPane.setAlignment(list, Pos.TOP_LEFT);
BorderPane.setMargin(list, new Insets(14,14,8,14));
BorderPane.setMargin(buttonPanel, new Insets(0,8,8,8));
bPane.setCenter(list);
bPane.setBottom(buttonPanel);
// Add Item Button action
btAddItem.setOnAction(e -> {
addNewItem();
list.setItems(FXCollections.observableArrayList(library.listAllItems())); // Update GUI
});
// Check Out Item Button action
btCheckOut.setOnAction(e -> {
checkOutItem();
list.setItems(FXCollections.observableArrayList(library.listAllItems())); // Update GUI
});
// Check In Item Button action
btCheckIn.setOnAction(e -> {
checkInItem();
list.setItems(FXCollections.observableArrayList(library.listAllItems())); // Update GUI
});
// Delete Item Button action
btDelete.setOnAction(e -> {
deleteItem();
list.setItems(FXCollections.observableArrayList(library.listAllItems())); // Update GUI
});
Scene scene = new Scene(bPane, 600, 600);
primaryStage.setTitle("Lending Library");
primaryStage.setScene(scene);
primaryStage.setWidth(bPane.getWidth());
primaryStage.setHeight(bPane.getHeight());
primaryStage.setResizable(false);
primaryStage.show();
// Save on close
primaryStage.setOnCloseRequest(e -> {
try {
library.save();
} catch (Exception exp) {
System.out.println("File did not save!");
} finally {
System.exit(0);
}
});
}
// Method to add an item in the list
public void addNewItem() {
String name = null, format = null;
TextInputDialog dialogBox = new TextInputDialog();
dialogBox.setTitle("Add Item");
dialogBox.setHeaderText(null);
dialogBox.setContentText("Name of Item:");
Optional<String> input = dialogBox.showAndWait();
if (input.isPresent()) {
name = input.get();
}
dialogBox.getEditor().clear();
dialogBox.setContentText("FormatType: ");
input = dialogBox.showAndWait();
if (input.isPresent()) {
format = input.get();
}
library.addNewItem(name, format);
try {
library.save();
} catch (Exception exc) {
System.out.println("File did not save!");
exc.printStackTrace();
}
}
// Method to delete an item in the list
public void deleteItem() {
Object selected = list.getSelectionModel().getSelectedItem();
String s = selected.toString();
String title = s.substring(0, s.lastIndexOf("("));
title = title.trim();
library.delete(title);
try {
library.save();
} catch (Exception exc) {
System.out.println("File did not save!");
exc.printStackTrace();
}
}
// Method to check out item in the list
public void checkOutItem() {
String name = null,
date = null;
TextInputDialog dialogBox = new TextInputDialog();
dialogBox.setTitle("Item Check Out");
dialogBox.setHeaderText(null);
dialogBox.setContentText("Enter Person Loaning To: ");
Optional<String> result = dialogBox.showAndWait();
if (result.isPresent()) {
name = result.get();
}
dialogBox.getEditor().clear();
dialogBox.setContentText("Date: ");
result = dialogBox.showAndWait();
if (result.isPresent()) {
date = result.get();
}
try {
library.markItemOnLoan(list.getSelectionModel().getSelectedIndex(), name, date);
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(null);
alert.setContentText(e.getMessage());
}
}
// Method to check in items in the list
public void checkInItem() {
Object selected = list.getSelectionModel().getSelectedItem(); // gets the selected item
String s = selected.toString(); // converts that to a String
String title = s.substring(0, s.lastIndexOf("(")); // extracts the title
title.trim(); // removes any trailing whitespace
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("Item Check In");
dialog.setHeaderText(null);
dialog.setContentText("Enter Title Returned: ");
try {
library.markItemReturned(list.getSelectionModel().getSelectedIndex());
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(null);
alert.setContentText(e.getMessage());
}
}
// Method to start GUI
public static void main(String[] args) {
Application.launch(args);
}
}
这是一个示例libraryItems.txt文件
%one%DVD%false%null%null
%two%DVD%false%null%null
%three%DVD%false%null%null
从我的“调试”控制台输出可以看出,在“public ArrayList listalItems”方法中,问题是何时发生的,但我不确定原因。我看过类似的问题,但它们似乎不起作用!在正确的方向轻推是赞赏的 项目创建代码位于
之外,而循环位于open()
中。这导致每个调用只创建一个实例。此实例会重复更新
您需要将项目创建移动到循环体中:
public void open() throws Exception {
try (Scanner fileInput = new Scanner(new File("libraryItems.txt"))) { // try-with resources makes sure that the Scanner is closed even on an error
fileInput.useDelimiter("%");
System.out.println("File opened!"); // Debugging console output
while (fileInput.hasNext()) {
MediaItem mItem = new MediaItem(); // create one item per line
mItem.setTitle(fileInput.next());
mItem.setFormat(fileInput.next());
mItem.setOnLoan(fileInput.nextBoolean());
String loanedTo = fileInput.next();
mItem.setLoanedTo(loanedTo != "null" ? loanedTo: null);
String itemStr = fileInput.next();
mItem.setDateLoaned(itemStr != "null" ? itemStr : null);
System.out.println(mItem.getTitle() + " (" + mItem.getFormat() + ") " + mItem.isOnLoan() +
" " + (mItem.isOnLoan() ? mItem.getLoanedTo() : "null") + " " +
(mItem.isOnLoan() ? mItem.getDateLoaned() : "null")); // Debugging console output
items.add(mItem);
System.out.println("Item added: " + mItem.getTitle()); // Debugging console output
System.out.println("Number of values in Item: " + items.size()); // Debugging console output
}
System.out.println("Number of values in Item: " + items.size()); // Debugging console output
}
}
您多次调用listalItems
,但是listalItems
resetsmasterList=newarraylist()代码>在正文中。这就解释了为什么只看到最后的值。要么从列表项
中删除这一行(假设它至少在其他地方初始化了,要么将其更改为主列表=主列表!=null?主列表:新的ArrayList();
),要么将列表.setItems
方法以某种方式附加到其collection@ernest_k不,没有。请注意,masterList
只能从listalItems
访问。您也可以将该字段转换为局部变量,它唯一会改变的是代码质量。@ernest_k我尝试了您的所有建议,但没有找到任何可行的解决方案,但感谢您的建议@谢谢你!这在正确读取文件内容方面起了作用!
%one%DVD%false%null%null
%two%DVD%false%null%null
%three%DVD%false%null%null
public void open() throws Exception {
try (Scanner fileInput = new Scanner(new File("libraryItems.txt"))) { // try-with resources makes sure that the Scanner is closed even on an error
fileInput.useDelimiter("%");
System.out.println("File opened!"); // Debugging console output
while (fileInput.hasNext()) {
MediaItem mItem = new MediaItem(); // create one item per line
mItem.setTitle(fileInput.next());
mItem.setFormat(fileInput.next());
mItem.setOnLoan(fileInput.nextBoolean());
String loanedTo = fileInput.next();
mItem.setLoanedTo(loanedTo != "null" ? loanedTo: null);
String itemStr = fileInput.next();
mItem.setDateLoaned(itemStr != "null" ? itemStr : null);
System.out.println(mItem.getTitle() + " (" + mItem.getFormat() + ") " + mItem.isOnLoan() +
" " + (mItem.isOnLoan() ? mItem.getLoanedTo() : "null") + " " +
(mItem.isOnLoan() ? mItem.getDateLoaned() : "null")); // Debugging console output
items.add(mItem);
System.out.println("Item added: " + mItem.getTitle()); // Debugging console output
System.out.println("Number of values in Item: " + items.size()); // Debugging console output
}
System.out.println("Number of values in Item: " + items.size()); // Debugging console output
}
}