So I have this project for my college and I'm stuck here, I tried everything I had in mind to make this code save more than 1 slot, as I must save up to 100 into a matrix database. Everything works great but the program always overwrites the first line, never passes on to the second...Here's the code:
Reserve part method:
for (n=1; n<100; n++) {
parkinglot[n][0] = Integer.toString(n);
parkinglot[n][1] = JOptionPane.showInputDialog(null, "License plate: ").toUpperCase();
String hourofreservation = JOptionPane.showInputDialog(null, "Reservation hour(hh:mm): ");
parkinglot[n][2] = hourofreservation;
parkinglot[n][3] = formatter.format(date);
parkingtime = Integer.parseInt(JOptionPane.showInputDialog(null, "Hours : "));
parkinglot[n][4] = Integer.toString(parkingtime);
int totalfee = (toMinutes(parkingtime)/30) * fee;
pay(totalfee);
//SaveReservation(nrinmat, parkinglot);
//save
JOptionPane.showMessageDialog(null, "This is yout reservation" + "\n\n" + " | " + parkinglot[n][0] + " | " + parkinglot[n][1] + " | " + parkinglot[n][2] + " | " + parkinglot[n][3] + " | " + parkinglot[n][4] + " HOURS |");
break;
}
Database method:
public static String[][] database(String [][]parkinglot)
{
System.out.println("This is database");
for (int i = 1; i < parkinglot.length; i++) {
for (int j = 0; j < parkinglot[i].length; j++) {
System.out.print(parkinglot[i][j] + "\t");
}
System.out.println();
}
return parkinglot;
}
Your program is starting at 1 every time because you have this line:
for (n=1; n<100; n++)
which initializes n
to 1 before you enter the loop. (As noted in a comment, usually you would initialize n
to zero, but that's not your problem here.)
Later, you break out of the loop, when n
is still 1. When you call this code again (I assume it's in a function), it reinitializes n
to 1 at the start of the loop. So n
is never anything other than 1.
If you only want to fill in one record each time you run the program, then you don't need a loop at all. You need to store the value of n
somewhere (like on disk, or in a database) and then read it back when you run the program again. Or, if you're saving the contents of parkinglot
somewhere and reading it back in, you could scan it (using a for
loop) to find the first empty entry, and initialize n
to that, something like:
int n = 1; // or 0
for (; n < parkinglot.length && parkinglot[n][0] != null; n++);
if (n < parkinglot.length) {
populateParkingLotEntry(parkinglot, n);
} else {
// No more slots left...
}