I have been creating a program that is to add search delete bookings etc...
After hours I finally thought I was making progress but when I delete a booking my program finds the correct booking returns the correct information for that booking but deletes a different booking.
I have attached the files in a zip as if I displayed them they would take up lots of screen space. The program has been made in BlueJay.
Code for decleration and adding of objects into my array list
public Hostel(String hostelName)
{
this.hostelName = "Newcastle Hostel";
bookings = new ArrayList<Booking>();
}
public String getHostelName()
{
return hostelName;
}
public String addBooking(String roomID, String roomType, String guest)
{
if (roomID.equals(""))
return "Error Please Entre Room ID";
else if (roomType.equals(""))
return "Error Please Entre Room Type";
else if (guest.equals(""))
return "Error Please Entre Guest Name";
bookings.add(new Booking(roomID,roomType,guest));
return "Room " + roomID + " " + roomType + " Has Been Booked For " + guest;
}
This is taken from my hostel class
public String deleteBooking(String roomID)
{
int index = 0;
for ( Booking s : bookings )
{
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
bookings.remove(index);
}
index++;
}
}
return " Cannot find room";
}
this is taken from my GUI class
else if (item.equals("Cancel Booking"))
{
newBookingButton.setEnabled(false);
cancelBookingButton.setEnabled(false);
String roomID = JOptionPane.showInputDialog(this, "Enter a room ID", "Delete a Booking", JOptionPane.QUESTION_MESSAGE);
output.setText(hostel.deleteBooking(roomID));
newBookingButton.setEnabled(true);
cancelBookingButton.setEnabled(true);
}
Any additonal code needed either ask or there is a full copy in the link above thanks
Your loop only increments the index if the room ID of the current room is equal to the ID of the room to delete. The line
index++;
should be out of the if block.
EDIT:
The other problem is that you're trying to remove elements a collection while iterating on it. This is only possible if you use an Iterator to iterate over the collection, and use the iterator's remove method to remove the current element. Note that even if it was possible, since you remove the element at the given index, the index should not be incremented since you have just removed the element at this index.
Example of using an iterator:
for (Iterator<Booking> it = bookings.iterator(); it.hasNext(); ) {
Booking b = it.next();
if (...) {
it.remove();
}
}
Basically when s.getRoomID().equals(roomID) is true your if block is executed so no matter what is the response of the user your index is incremented. So, do this:
if ( s.getRoomID().equals(roomID))
{
//your code
}
index++
I just looked into your code, and seems like you are trying to iterate over a collection and also modifying the values at the same time. With enhanced for loop, such things do give errors, so instead of using the enhanced for loop, you must use a normal for loop. So I had modified your deleteBookings Method for the respective change.
public String deleteBooking(String roomID)
{
//for ( Booking s : bookings )
for (int i = 0; i < bookings.size(); i++)
{
Booking s = bookings.get(i);
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
//int r = JOptionPane.showOptionDialog,null("Are you sure you would like to delete the following \n"
//+ "deleteMessage",
//"Delete a booking",
//JOptionPane.YES_NO_OPTION,
//JOptionPane.QUESTION_MESSAGE,null,null,null);
//if (r == JOptionPane.YES_OPTION) {
// bookings.remove(index);
//}
//if (r == JOptionPane.NO_OPTION){
// return "Booking Was Not Canceled";
// }
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
//bookings.remove(index);
bookings.remove(i);
return deleteMessage + " has been DELETED."; /*I did this.*/
}
}
}
return " Cannot find room";
}
Moreover, after this
bookings.remove(i);
You forgot to return something like
return deleteMessage + " has been DELETED."; /*I did this.*/
Since you failed to return a String on successful completion, that's the reason why it returns "Cannot find room.", even after successful deletion.
Rest of the code is perfect.
Hope that might solve your query.
Regards
Related
Sorry for my English, but how am I suppose to run the ERROR MESSAGE without repeating 3 times?
This is the original one, if I run the ERROR JOptionPane it will repeat 3 times
String name = JOptionPane.showInputDialog(null, "Enter the Student name to search:", "Input", JOptionPane.QUESTION_MESSAGE);
String data = ("Cannot find the student \"" + name + "\"!!");
for (int i = 0; i < student.length; i++){
if(name.equals(student[i].getName())){
data = ("\n Course \t Admin# \t Name \n" + student[i].getName() + student[i].getAdminNum() + student[i].getCourse() + student[i].getGpa() + student[i].getNewModule() + "\n");
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.INFORMATION_MESSAGE);
}
Else{
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.ERROR_MESSAGE);
}
And this is the current one, which the if else statement is wrong as I couldn't read the original data
String name = JOptionPane.showInputDialog(null, "Enter the Student name to search:", "Input", JOptionPane.QUESTION_MESSAGE);
String data = ("Cannot find the student \"" + name + "\"!!");
for (int i = 0; i < student.length; i++){
if(name.equals(student[i].getName())){
data = ("\n Course \t Admin# \t Name \n" + student[i].getName() + student[i].getAdminNum() + student[i].getCourse() + student[i].getGpa() + student[i].getNewModule() + "\n");
}
}
if(data != data){
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.ERROR_MESSAGE);
}
I'm so sorry if there is any misconception thinking passes to you all due to my broken English.
If i undertand your answer, you are finding the "continue" function.
This one breaks de for loop.
https://www.w3schools.com/java/java_break.asp
Create a local variable of name say not_found (int) and increment this found variable in else part instead of showing Dialog everytime.
After end of for loop, check for found variable and display dialog box according to your requirements.
int not_found=0;
String name = JOptionPane.showInputDialog(null, "Enter the Student name to
search:", "Input", JOptionPane.QUESTION_MESSAGE);
String data = ("Cannot find the student \"" + name + "\"!!");
for (int i = 0; i < student.length; i++){
if(name.equals(student[i].getName())){
data = ("\n Course \t Admin# \t Name \n" + student[i].getName()
+ student[i].getAdminNum() + student[i].getCourse() + student[i].getGpa() +
student[i].getNewModule() + "\n");
JOptionPane.showMessageDialog(null, data, "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else{
not_found++:
}
if(not_found!=0){
JOptionPane.showMessageDialog(null, data,
"Message",OptionPane.ERROR_MESSAGE);
}
I have a "bank" program, with the following chunk of code:
private void doPayment(JTextField accountNumField, JTextField paymentField)
{
int accountNum = Integer.parseInt(accountNumField.getText());
double paymentAmt = Double.parseDouble(paymentField.getText());
String paymentProcessed = "-RECEIPT OF PAYMENT-" + "\n\n" + "Account Number:" + " " + accountObject.getAccountNum() + "Beginning Balance:" + " " + accountObject.getBegBalance()
+ "Payment Amount:" + " " + accountObject.getPaymentAmount() + "Ending Balance:" + " " + accountObject.getEndBalance();
String errorMsg = "ERROR: ACCOUNT NUMBER" + " " + "[" + accountObject.getAccountNum() + "]" + " " + "NOT FOUND. PLEASE VERIFY THAT THE ACCOUNT INFORMATION IS VALID AND CORRECT.";
if (accountsArrayList.contains(accountNum))
{
accountObject.transactionTwo(paymentAmt);
JOptionPane.showMessageDialog(null, paymentProcessed, "PAYMENT PROCESSED SUCCESSFULLY", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, errorMsg, "INVALID ACCOUNT ERROR", JOptionPane.PLAIN_MESSAGE);
}
}
In theory, after the user creates the account for the client, he/she navigates to a "Process Payment" window and enters two things: accountNum and paymentAmt then hits submit, at which point the doPayment method is called.
This method is supposed to work such that the program iterates through the accountsArrayList which contains THREE items: lastName, firstName, and accountNum. If it finds that the accountNum provided matches a prexisting accountNum in the arrayList, then the transaction is processed accordingly. If no matching accountNum can be found then it returns an error message.
At present, it just returns the error message in the else part of the if-else. I thought that the contains(item) method automatically iterates through the Arraylist. If that isn't the case, do I need an enhanced FOR-loop?
if (accountsArrayList.contains(accountNum))
accountsArrayList is a ArrayList which contains Objects of type Account.
contains returns true only if accountsArrayList contains an Object type Account given as argument. In your code, accountNum is a int
so the compiler reads it like if(Account == INTEGER)
You have to go throw each Account in your ArrayList and get it's accountNum and than compare the values.
for(int i = 0; i < accountsArrayList.size; i++){
if(accountsArrayList.get(i).accountNum == accountNum){
//success
}
else {
//error
}
}
For a few projects, I've been trying to make a console menu in Java similar to:
(1) Do this
(2) Do that
(3) Blah blah
(4) etc
I'm using a do {...} while (...) loop but I can't get the right value for the controlling variable.
The code I had was:
String status = "e";
do {
System.out.println("---------------------------------------");
System.out.println(b1.toString());
System.out.println(b2.toString());
System.out.println(b3.toString());
System.out.println("---------------------------------------");
System.out.println("Borrow(b), Return(r), Check(c), Exit(e)");
status = r.nextLine();
....
} while(!status.equals("e"));
This code resulted in all the printlns outputting correctly, but upon pressing enter, the same thing would output again and the code I replaced with .... will not excute. This code had other console outputs which never came about.
I thought this was because the value returned by r.nextLine() continually changes as new data gets outputted. So I made a separate static function:
public static String getInfo(Scanner r, Book b1, Book b2, Book b3) {
System.out.println("---------------------------------------");
System.out.println(b1.toString());
System.out.println(b2.toString());
System.out.println(b3.toString());
System.out.println("---------------------------------------");
System.out.println("Borrow(b), Return(r), Check(c), Exit(e)");
String status = r.nextLine();
return status;
}
But this function also returns the same result. What can I do to fix this problem?
Edit:
Right now, this is my full code for the menu portion, this runs in the main.
`String status = "e";
do {
status = getInfo(reader,b1,b2,b3);
if (status == "b") {
System.out.println("Which patron ( (1)" + p.getName() + " or (2)" + p2.getName() + " is borrowing?");
int cur = reader.nextInt();
System.out.println("Which book is " + cur + " borrowing?");
String curbk = reader.nextLine();
if (p.hasBook(curbk)){
System.out.println(p.getName() + " has this book already.");
} else {
if (p2.hasBook(curbk)) {
System.out.println(p2.getName() + " has this book already.");
} else {
if (cur==1) {
System.out.println(p.borrowBook(curbk));
} else {
System.out.println(p2.borrowBook(curbk));
}
}
}
} else if (status == "r") {
System.out.println("Which patron ( (1)" + p.getName() + " or (2)" + p2.getName() + ") is returning?");
int cur = reader.nextInt();
System.out.println("Which book is " + cur + " returning?");
String curbk = reader.nextLine();
if (cur==1) {
if (p.hasBook(curbk)){
System.out.println(p.returnBook(curbk));
} else {
System.out.println(p.getName() + " does not have this book.");
}
} else {
if (p2.hasBook(curbk)){
System.out.println(p2.returnBook(curbk));
} else {
System.out.println(p2.getName() + " does not have this book.");
}
}
} else if (status == "c") {
System.out.println("Which book would you like to check for?");
String curbk = reader.nextLine();
if (p.hasBook(curbk)){
System.out.println(p.getName() + " has this book.");
} else {
if (p2.hasBook(curbk)) {
System.out.println(p2.getName() + " has this book.");
} else {
System.out.println("This book is ready to be checked out!");
}
}
}
} while(!status.equals("e"));`
The getInfo() is from above.
String status = r.nextLine();
Remove the keyword String, as it's creating a new String rather than using the variable you already created.
I want to search object inside arraylist get value from user input and print it to text area. here is the code.
//the arrayList I declared
Book[]myBook = new Book [30];
int index = 0;
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String title = titleTF.getText();
boolean found = false;
for (int i = 0; i < index; i++) {
if (myBook[i].getTitle().equals(title));
{
outputTA.append("Book Title : " + myBook[i].getTitle() + "\n");
outputTA.append("Book Author : " + myBook[i].getAuthor() + "\n");
outputTA.append("Year of Publication : " + myBook[i].getYear() + "\n");
outputTA.append("Book Status : " + myBook[i].getStatus() + "\n");
outputTA.append("======================================\n");
found = true;
break;
}
}
if (found == false) {
JOptionPane.showMessageDialog(this, "Book is not Found! Please Try again!");
}
}
The problem is, when I click the search button, it will display the first object in the arraylist. Which line of code is wrong?
First off, your index is 0 so your for doesn't loop. Replace index with myBook.size()
i can't figure out how to tell the user that there is "no such title found" when they go to search for a title. when i test it and type in a title from the database it shows the correct information:
Game Id: 2
Title: Goldeneye 007
Rating: T
Platform: Nintendo 64
Developer: RockStar
but if i type in random information the output looks like this:
Game Id: 0
Title: asdsdfdfg
Rating: null
Platform: null
Developer: null
i'm using a basic console application in java with mysql i have two layers.
my presentation layer:
private static Games SearchForGame() {
Logic aref = new Logic();
Games g = new Games();
#SuppressWarnings("resource")
Scanner scanline = new Scanner(System.in);
System.out.println("Please enter the name of the game you wish to find:");
g.setTitle(scanline.nextLine());
aref.SearchGame(g);
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
return g;
}
and a logic layer
public Games SearchGame(Games g) {
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
String sql = "SELECT GameId,Title,Rating,Platform,Developer FROM games WHERE Title=?";
java.sql.PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, g.getTitle());
ResultSet rs = statement.executeQuery();
while(rs.next()){
g.setGameId(rs.getInt("GameId"));
g.setTitle(rs.getString("Title"));
g.setRating(rs.getString("Rating"));
g.setPlatform(rs.getString("Platform"));
g.setDeveloper(rs.getString("Developer"));
}
} catch (Exception e) {
e.printStackTrace();
}
return g;
}
Use an if statement?
if(g.getRating() != null /*or g.getGameId() == 0 or many other things*/) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
} else {
System.out.println();
System.out.println("No such title found");
//throw some sort of exception (and plan to catch it) so that you
//can get out of this method without returning g full of null values
}
return g;
You can do that in many ways, will explain one here.
In SearchGame method use isBeforeFirst() method to check if you have any data at all.
if(!resultSet.isBeforeFirst()){
return null;
}
And in your SearchForGame() if the object is null, display a message.
if(g != null) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
} else {
System.out.println("No data found");
}
Checking nulls is a bad form of flow control. You should consider a boolean result instead.
if(aref.SearchGame(g)) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
. . .
else {
System.out.println("No such title found");
}
Then in your logic, just do this:
public boolean SearchGame(Games g) {
boolean found = false;
try {
[your sql select here]
if (rs.next()) {
[access result set]
found = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return found;
}
But an even better way is to return a list of Game instance and then check if that list is empty, like this.
List<Game> SearchGames(String title)
That's a good solid API, and you could use it like this:
List<Game> games = aref.SearchGames(title);
if(games.size() > 0) {
Game g = games.get(0);
System.out.println();
System.out.println("Game Id: " + g.getGameId());
. . .
else {
System.out.println("No such title found");
}
This also allows you to find multiple Games with similar titles if you wanted.