In one of my project, my teacher required us to write a basic save/load into a XML for an example parking lot, and while this load object work OK:
public void saveToXml() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// Create the root element <parkingLot>
Document doc = docBuilder.newDocument();
Element parkingLotElement = doc.createElement("parkingLot");
doc.appendChild(parkingLotElement);
// Create the <parkingLotId> element
Element parkingLotIdElement = doc.createElement("parkingLotId");
parkingLotIdElement.appendChild(doc.createTextNode(parkingLotId));
parkingLotElement.appendChild(parkingLotIdElement);
// Create the <slots> element
Element slotsElement = doc.createElement("slots");
parkingLotElement.appendChild(slotsElement);
// Create the <floor> elements based on the number of floors
for (List<Slot> floor : slots) {
Element floorElement = doc.createElement("floor");
slotsElement.appendChild(floorElement);
// Create the <slot> elements within each floor
for (Slot slot : floor) {
Element slotElement = doc.createElement("slot");
floorElement.appendChild(slotElement);
// Check if the slot has a car parked in it
if (slot.isOccupied()) {
Car car = slot.getCar();
// Create the <car> element
Element carElement = doc.createElement("car");
slotElement.appendChild(carElement);
// Create the <registrationNumber> element
Element regNumberElement = doc.createElement("registrationNumber");
regNumberElement.appendChild(doc.createTextNode(car.getRegNo()));
carElement.appendChild(regNumberElement);
// Create the <name> element
Element nameElement = doc.createElement("name");
nameElement.appendChild(doc.createTextNode(car.getName()));
carElement.appendChild(nameElement);
// Create the <parkingDuration> element
Element durationElement = doc.createElement("parkingDuration");
durationElement.appendChild(doc.createTextNode(String.valueOf(car.getParkingDuration())));
carElement.appendChild(durationElement);
}
else {
// Create the <car> element for empty slot
Element carElement = doc.createElement("car");
slotElement.appendChild(carElement);
// Create the <registrationNumber> element for empty slot
Element regNumberElement = doc.createElement("registrationNumber");
regNumberElement.appendChild(doc.createTextNode("empty"));
carElement.appendChild(regNumberElement);
// Create the <name> element for empty slot
Element nameElement = doc.createElement("name");
nameElement.appendChild(doc.createTextNode("empty"));
carElement.appendChild(nameElement);
// Create the <parkingDuration> element for empty slot
Element durationElement = doc.createElement("parkingDuration");
durationElement.appendChild(doc.createTextNode("0"));
carElement.appendChild(durationElement);
}
}
}
// Create the <totalCars> element
Element totalCarsElement = doc.createElement("totalCars");
totalCarsElement.appendChild(doc.createTextNode(String.valueOf(totalCars)));
parkingLotElement.appendChild(totalCarsElement);
// Write the XML content to a file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("parking_lot.xml"));
transformer.transform(source, result);
System.out.println("XML file saved successfully.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
This load button do work:
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
File xmlFile = new File("parking_lot.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFile);
// Get the root element <parkingLot>
Element parkingLotElement = doc.getDocumentElement();
// Get the <parkingLotId> element and retrieve the value
String parkingLotId = parkingLotElement.getElementsByTagName("parkingLotId").item(0).getTextContent();
// Get the <slots> element
Element slotsElement = (Element) parkingLotElement.getElementsByTagName("slots").item(0);
// Create a new ParkingLot object with the retrieved data
parkingLot.setParkingLotId(parkingLotId);;
// Process the <floor> and <slot> elements to populate the slots
NodeList floorList = slotsElement.getElementsByTagName("floor");
for (int i = 0; i < floorList.getLength(); i++) {
Node floorNode = floorList.item(i);
if (floorNode.getNodeType() == Node.ELEMENT_NODE) {
Element floorElement = (Element) floorNode;
NodeList slotList = floorElement.getElementsByTagName("slot");
ArrayList<Slot> floorSlots = new ArrayList<>();
for (int j = 0; j < slotList.getLength(); j++) {
Node slotNode = slotList.item(j);
if (slotNode.getNodeType() == Node.ELEMENT_NODE) {
Element slotElement = (Element) slotNode;
if (slotElement.hasChildNodes()) {
// Process the <car> element to retrieve car details
Element carElement = (Element) slotElement.getElementsByTagName("car").item(0);
String registrationNumber = carElement.getElementsByTagName("registrationNumber").item(0).getTextContent();
String name = carElement.getElementsByTagName("name").item(0).getTextContent();
int parkingDuration = Integer.parseInt(carElement.getElementsByTagName("parkingDuration").item(0).getTextContent());
// Create a new Car object and add it to the slot
Car car = new Car(registrationNumber, name, parkingDuration);
Slot slot = new Slot();
slot.setCar(car);
floorSlots.add(slot);
} else {
// Create an empty slot
floorSlots.add(new Slot());
}
}
}
// Add the floorSlots list to the slots list of the parkingLot object
parkingLot.getSlots().add(floorSlots);
}
}
// Get the <totalCars> element and retrieve the value
int totalCars = Integer.parseInt(parkingLotElement.getElementsByTagName("totalCars").item(0).getTextContent());
// Update the instance variable totalCars directly
parkingLot.setTotalCars(totalCars);
System.out.println("Data loaded from XML successfully.");
} catch (Exception ex) {
ex.printStackTrace();
}
JOptionPane.showMessageDialog(this, "Load complete!");
}private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
File xmlFile = new File("parking_lot.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFile);
// Get the root element <parkingLot>
Element parkingLotElement = doc.getDocumentElement();
// Get the <parkingLotId> element and retrieve the value
String parkingLotId = parkingLotElement.getElementsByTagName("parkingLotId").item(0).getTextContent();
// Get the <slots> element
Element slotsElement = (Element) parkingLotElement.getElementsByTagName("slots").item(0);
// Create a new ParkingLot object with the retrieved data
parkingLot.setParkingLotId(parkingLotId);;
// Process the <floor> and <slot> elements to populate the slots
NodeList floorList = slotsElement.getElementsByTagName("floor");
for (int i = 0; i < floorList.getLength(); i++) {
Node floorNode = floorList.item(i);
if (floorNode.getNodeType() == Node.ELEMENT_NODE) {
Element floorElement = (Element) floorNode;
NodeList slotList = floorElement.getElementsByTagName("slot");
ArrayList<Slot> floorSlots = new ArrayList<>();
for (int j = 0; j < slotList.getLength(); j++) {
Node slotNode = slotList.item(j);
if (slotNode.getNodeType() == Node.ELEMENT_NODE) {
Element slotElement = (Element) slotNode;
if (slotElement.hasChildNodes()) {
// Process the <car> element to retrieve car details
Element carElement = (Element) slotElement.getElementsByTagName("car").item(0);
String registrationNumber = carElement.getElementsByTagName("registrationNumber").item(0).getTextContent();
String name = carElement.getElementsByTagName("name").item(0).getTextContent();
int parkingDuration = Integer.parseInt(carElement.getElementsByTagName("parkingDuration").item(0).getTextContent());
// Create a new Car object and add it to the slot
Car car = new Car(registrationNumber, name, parkingDuration);
Slot slot = new Slot();
slot.setCar(car);
floorSlots.add(slot);
} else {
// Create an empty slot
floorSlots.add(new Slot());
}
}
}
// Add the floorSlots list to the slots list of the parkingLot object
parkingLot.getSlots().add(floorSlots);
}
}
// Get the <totalCars> element and retrieve the value
int totalCars = Integer.parseInt(parkingLotElement.getElementsByTagName("totalCars").item(0).getTextContent());
// Update the instance variable totalCars directly
parkingLot.setTotalCars(totalCars);
System.out.println("Data loaded from XML successfully.");
} catch (Exception ex) {
ex.printStackTrace();
}
JOptionPane.showMessageDialog(this, "Load complete!");
}
but then there is a problem with a button:
private void btnPropertiesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPropertiesActionPerformed
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parkingLot.getFloors(); i++) {
for (int j = 0; j < parkingLot.getSlotsPerFloor(); j++) {
Slot slot = parkingLot.getSlot(i, j);
String slotInfo = "Tầng " + (i + 1) + " Chỗ " + (j + 1) + ": ";
if (slot.isOccupied()) {
Car car = slot.getCar();
String regNo = car.getRegNo();
String name = car.getName();
String parkingDurationStr = txtParkingDuration.getText();
int parkingDuration = Integer.parseInt(parkingDurationStr);
if (regNo.equals("empty") && name.equals("empty") && parkingDuration == 0) {
slotInfo += "Empty slot";
} else {
slotInfo += regNo + " / " + name + " / " + parkingDuration + " giờ";
}
} else {
slotInfo += "Chỗ trống";
}
sb.append(slotInfo).append("n"); // Append slotInfo to sb
}
this button keep giving “Exception in thread “AWT-EventQueue-0” java.lang.NumberFormatException: For input string: “” “
i have changed the button to this:
private void btnPropertiesActionPerformed(java.awt.event.ActionEvent evt) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parkingLot.getFloors(); i++) {
for (int j = 0; j < parkingLot.getSlotsPerFloor(); j++) {
Slot slot = parkingLot.getSlot(i, j);
String slotInfo = "Tầng " + (i + 1) + " Chỗ " + (j + 1) + ": ";
if (slot.isOccupied()) {
Car car = slot.getCar();
String regNo = car.getRegNo();
String name = car.getName();
int parkingDuration;
try {
parkingDuration = Integer.parseInt(txtParkingDuration.getText()); // Parse the parking duration directly from the text field
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,
"Invalid parking duration.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (regNo.equals("empty") && name.equals("empty") && parkingDuration == 0) {
slotInfo += "Empty slot";
} else {
slotInfo += regNo + " / " + name + " / " + parkingDuration + " giờ";
}
} else {
slotInfo += "Chỗ trống";
}
sb.append(slotInfo).append("n"); // Append slotInfo to sb
JOptionPane.showMessageDialog(this,
"Biển số / Tên chủ xe / Thời hạn gửi n" + sb.toString(),
"Tình trạng bãi gửi xe", JOptionPane.INFORMATION_MESSAGE);
}
}
}
but then the button keep loading each slot in instead of loading the whole status of the parking lot.
Also here’s the XML just in case:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<parkingLot>
<parkingLotId>F</parkingLotId>
<slots>
<floor>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>1</registrationNumber>
<name>thai</name>
<parkingDuration>10</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
</floor>
<floor>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
</floor>
<floor>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
<slot>
<car>
<registrationNumber>empty</registrationNumber>
<name>empty</name>
<parkingDuration>0</parkingDuration>
</car>
</slot>
</floor>
</slots>
<totalCars>1</totalCars>
</parkingLot>
Since I’m still pretty new, can anyone lend a hand and have an explanation for what’s wrong in any part?
MCxGamez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2