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.
Related
Hello to whoever is reading this,
i am working on a plugin that amount other things lets you add a scoreboard with your deaths, but for the life of me i cannot figure out how to remove a scoreboard from a player, i am trying player.setScoreboard(null); but that does not seem to work, is there anyway somebody could tell me how to remove a scoreboard this is what i have
List<String> pop = new ArrayList<String>();
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (label.equalsIgnoreCase("scorecount")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You cannot do that console!");
return true;
}
if (sender.hasPermission("scorecount.use")) {
if (args.length == 3) {
this.sendInvalid(sender);
Player pvp = Bukkit.getPlayer((String)args[1]);
if (pvp == null) {
sender.sendMessage((Object)ChatColor.RED + "Player " + args[1] + " is not online.");
return true;
}
if (args[0].equalsIgnoreCase("add")) {
if (pop.contains(pvp.getName())) {
sender.sendMessage((Object)ChatColor.RED + pvp.getName() + " Already has a ScoreList!");
return true;
}
pop.add(pvp.getName());
sender.sendMessage((Object)ChatColor.GREEN + pvp.getName() + " Now has the ScoreList!");
ScoreboardManager manager = Bukkit.getScoreboardManager();
Scoreboard board = (Scoreboard) manager.getNewScoreboard();
Objective obj = board.registerNewObjective("pvpScoreboard", "dummy", ChatColor.translateAlternateColorCodes('&', "&a&l<< &2&lPvP &a&l>>"));
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
Score score = obj.getScore("____________");
score.setScore(3);
Score score2 = obj.getScore(ChatColor.AQUA + "Online Players: " + ChatColor.DARK_AQUA + Bukkit.getOnlinePlayers().size());
score2.setScore(2);
Score score3 = obj.getScore(ChatColor.AQUA + "Total Kills(mobs): " + ChatColor.DARK_AQUA + pvp.getStatistic(Statistic.MOB_KILLS));
score3.setScore(3);
pvp.setScoreboard(board);
pop.add(pvp.getName());
return true;
}
} else if (args.length == 2) {
Player player = Bukkit.getPlayer((String)args[1]);
if (player == null) {
sender.sendMessage((Object)ChatColor.RED + "Player " + args[1] + " is not online.");
return true;
}
if (args[0].equalsIgnoreCase("remove")) {
sender.sendMessage("Help");
Player pvp = Bukkit.getPlayer((String)args[1]);
pvp.setScoreboard(null);
pop.remove(pvp.getName());
sender.sendMessage((Object)ChatColor.GREEN + pvp.getName() + " no Longer has a Socrecount!");
pvp.setScoreboard(null);
pop.remove(pvp.getName());
return true;
}
}
}
}
return false;
}
private void sendInvalid(CommandSender sender) {
sender.sendMessage((Object)ChatColor.RED + "Invalid usage. Please use:");
sender.sendMessage((Object)ChatColor.RED + "/scorecount add <player>");
sender.sendMessage((Object)ChatColor.RED + "/scorecount remove <player>");
}
}
}```
I've not worked with Bukkit before, and I can't find the API documentation, but this tutorial suggests you need to do the following to "remove" a player's scoreboard:
pvp.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
I'm trying to make a program that will allow the user to input either a name or symbol of an element from the periodic table, and will then output some data about that element. So far I've managed to get the user to be able to input either a name or a symbol and have it output correctly, but if the user inputs something wrong then the code doesn't output anything, and will stop accepting an input of a symbol and only accept an input of a name. I would like to know how I would be able to break out of the loop and tell a user that their input is invalid only after the input has been checked against every item in the enum, since my current solution doesn't work. I'm new to Java, so a simple explanation as to how and why would be greatly appreciated.
import java.util.Scanner;
public class PeriodicTable {
public enum Element {
Hydrogen("H", "Nonmetal", "1.008"),
Helium("He", "Noble Gas", "4.003"),
Lithium("Li", "Alkali Metal", "6.941"),
Beryllium("Be", "Alkaline Earth", "9.012"),
Boron("B", "Semimetal", "10.811"),
Carbon("C", "Nonmetal", "12.011"),
//The rest of the periodic table is here, I just removed it for the sake of this post.
private String symbol;
private String group;
private String weight;
private Element(String symbol, String group, String weight) {
this.symbol = symbol;
this.group = group;
this.weight = weight;
}
}
static Element cName = null;
public static void main(String[] args) {
int counter = 0;
System.out.println("Enter the name or symbol of an element in the periodic table. ");
outer:
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
reader.close();
break outer;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break outer;
} catch(IllegalArgumentException e) {
if(counter > Element.values().length) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue outer;
} else {
counter++;
continue;
}
}
}
}
} while (true);
}
}
I would avoid using the valueOf method in a loop. Instead, you can iterate over the elements and for each element check both its name (use the name method) and its symbol.
Scanner reader = new Scanner(System.in);
outer: while (true) {
System.out.println("Enter the name or symbol of an element in the periodic table. ");
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input) || sy.name().equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
break outer;
}
}
System.out.println("No such element found. ");
}
reader.close(); // this might be a bad idea
I would also avoid closing the reader, as this will also close System.in and you will be unable to read any more input.
Assuming I understand your question, I would add the logic for parsing Element(s) to Element. You can create Map(s), one to symbol and one of name to corresponding Element instances and then invoke them in whichever order you choose. Like,
private static Map<String, Element> symbolMap = new HashMap<>();
private static Map<String, Element> nameMap = new HashMap<>();
static {
for (Element e : Element.values()) {
symbolMap.put(e.symbol.toUpperCase(), e);
nameMap.put(e.name().toUpperCase(), e);
}
}
public static Element fromString(String token) {
if (symbolMap.containsKey(token.toUpperCase())) {
return symbolMap.get(token.toUpperCase());
}
return nameMap.get(token.toUpperCase());
}
Then in main
Element e = Element.fromString("H");
Element e2 = Element.fromString("Hydrogen");
System.out.println(e == e2); // <-- true
And if e were null then it isn't a valid symbol (or name).
If I have understood correctly, you want to go through the enums and see if any of the symbols match the user input. If not, print a message and try again. You had the right approach, but in the catch block you don't need to make a counter. Instead if we think through the design, you have break outer; if the input ever matches. So the end of the do-while loop will only be reached if there is no matching element. So if we just print a message at the end, this will accomplish our goal:
outer:
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
reader.close();
break outer;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break outer;
} catch(IllegalArgumentException e) {
continue;
}
}
}
System.out.println("Error. No matching elements. Please try again.");
} while (true);
Sample Output:
Enter the name or symbol of an element in the periodic table.
No
Error. No matching elements. Please try again.
l
Error. No matching elements. Please try again.
He
Element: Helium (He)
Group: Noble Gas
Atomic Mass: 4.003
You complicate the code by mixing the search for the name and the search for the symbol. The search for the name does not need to be inside the for loop:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the name or symbol of an element in the periodic table. ");
boolean found = false;
do {
String input = reader.nextLine().trim();
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
found = true;
} catch (IllegalArgumentException e) {
}
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
found = true;
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
}
}
if (!found)
System.out.println("That name or symbol is not valid. Please try again. ");
} while (!found);
reader.close();
}
So I had to create a method that separated input string into first/middle/last names, counted the number of "students" created, etc, and then I had to create a class that tested those methods.
public void setName(String newName)
{
String[] nameInput = newName.split(" ");
if(nameInput.length == 0)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if(nameInput.length == 1)
{
firstName = nameInput[0];
middleName = "";
lastName = nameInput[1];
newName = firstName + lastName;
}
else if(nameInput.length == 2)
{
firstName = nameInput[0];
middleName = nameInput[1];
lastName = nameInput[2];
newName = firstName + middleName + lastName;
}
else
{
System.out.println("Error! You can only enter up to three names.");
}
}
public String getName()
{
if (middleName == null)
{
return firstName + " " + lastName;
}
else
return firstName + " " + middleName + " " + lastName;
}
public String getId()
{
return identifier = generateID();
}
#Override
public String toString()
{
return getName() + "\n" + "(" + generateID() + ")";
}
private String generateID()
{
return UUID.randomUUID().toString();
}
and this is the way I am testing the code:
public static void testStudent()
{
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
testStudent1 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
testStudent1 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
}
I keep running into a null pointer exceptions when it tests toString for a student with 2 names, and I have no clue why.
Edit: The issue is with the testStudent variable in the testStudent() method.
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
Student testStudent2 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
Student testStudent3 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
Since you are re-using the testStudent1 variable to create a new Object of Student class and not using them to invoke getter functions, it will throw an NPE for testStudent2 and testStudent3 variables.
Answer for old issue: The issue is with your while statement. It will never stop.
You can just find out the count by doing nameInput.length for the String array.
It should be like this:
String[] nameInput = newName.split(" ");
if (nameInput.length == 1)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if (nameInput.length == 2)
{
...
}
else if (nameInput.length == 3)
{
...
}
else
{
...
}
You could use StringTokenizer class to help you with this.
import java.util.StringTokenizer
StringTokenizer test = new StringTokenizer("An example string");
while (test.hasMoreTokens()) {
System.out.println(test.nextToken());
}
Output:
An
example
string.
The countTokens() method can provide how many tokens a string will provide prior processing. That way you will know if you have a middle name or not.
please check trim() method
public static void getName(String newName) {
newName = newName.trim();
String fullName = null;
String[] nameInput = newName.split(" ");
switch (nameInput.length) {
case 2:
fullName = mergeName(nameInput[0], "", nameInput[1]);
break;
case 3:
fullName = mergeName(nameInput[0], nameInput[1], nameInput[2]);
break;
default:
System.out.println("Error, please enter at least two names.");
break;
}
System.out.println(fullName);
}
public static String mergeName(String firstName, String middleName,
String lastName) {
String name = firstName+" " + middleName+" " + lastName;
return name;
}
I am working on a java program for creating a slot machine. The program works how I want it to but I am not sure if one of my method calls is proper java etiquette. In my main method below, inside my for loop, I call the method rollAndCompare() on the FourTumblers object, machine. This method returns an integer, coin, which represents how much the user won based on the number of tumblers matched. This if-else statement is written in the FourTumblers class. However, I also pass the same machine object as a parameter so that the method can access the tumbler values of the object. Is there a better way to do this? Is this correct?
public static void main(String[] args) {
int coins;
int addtLives;
int bank = 0;
int lives = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter how many games you want to play:");
int num = scan.nextInt();
System.out.println("You have decided to play " + num + " games.\n");
for (int i = 1; i <= num; i++) {
FourTumblers machine = new FourTumblers();
coins = machine.rollAndCompare(machine);
bank += coins;
addtLives = coins/100;
lives += addtLives;
System.out.println("You won " + coins + " coins. That's " + addtLives + " lives.");
System.out.println("You now have a total of " + bank + " coins and " + lives + " lives.\n");
}
scan.close();
}
Here is my rollAndCompare method...
public int rollAndCompare(FourTumblers machine) {
value1 = machine.getValue1();
value2 = machine.getValue2();
value3 = machine.getValue3();
value4 = machine.getValue4();
if ((value1 == value2)&&(value2 == value3)&&(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
System.out.println("Jackpot!");
coins = 600;
return coins;
}
else if (((value1 == value2)&&(value2 == value3))||((value1 == value3)&&(value3 == value4))||((value1 == value2)&&(value2 == value4))||((value2 == value3)&&(value3 == value4))){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 300;
return coins;
}
else if ((value1 == value4)||(value1 == value2)||(value1 == value3)||(value2 == value3)||(value2 == value4)||(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 100;
return coins;
}
else{
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 0;
return coins;
}
}
The times you would want to add an object onto itself in a class is if you are going to compare it with other objects from the same class.
Ex:
public class Sample
{
private String name = "Sample Chocolate";
private int cost = 1;
public boolean compareSample(Sample sample)
{
if (sample.name.equals(name) && cost == sample.cost)
return true;
else
return false;
}
Then from another class:
public class SampleTester
{
public static void main(String[] args)
{
Sample sample1 = new Sample();
Sample sample2 = new Sample();
System.out.println("Are sample one and sample two the same?: " + sample1.compareSample(sample2));
}
}
Otherwise you can simply put nothing inside the parenthesis:
public boolean compareSample()
{
if (name.equals("Sample Chocolate") && cost == 1)
return true;
else
return false;
}
As Ashiquzzman eloquently said: You can call that using this.getValue(), you don't need to pass machine (to be used as machine.getValue()).
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