Checking if user input contains an item - java

In my text-adventure game one of the commands is "take" which requires the user to enter both the letter 'T' and an item that is in the room they are in.
I have taken this input and split it into command and item, but I'm having trouble with the if statement. I have the first part that checks if the command section is equal to 'T', but I have to also check if this input has an "item" section to it. I tried using .isEmpty() and != null as well as using .contains().
Here is my code:
public Command getCommandFromResponse(String response) throws IllegalArgumentException{
String[] split = response.split(" ");
if (split.length < 1){
throw new IllegalArgumentException("Invalid command.");
}
Command command = new Command(split[0]);
if (split.length >= 2) {
command.setItem(split[1]);
}
return command;
}
This is the take method:
else if(userCommand.command.equalsIgnoreCase("T") && /*if userCommand contains an item*/){
//Split the input String into two parts, command and item
userCommand = getCommandFromResponse(userInput.nextLine());
if (locale.item != null) {
if (userCommand.item.equalsIgnoreCase(locale.item.itemName)) {
//add the item to the player's inventory
player1.inventory.add(locale.item);
System.out.println("\tA " + locale.item + " was added to your inventory");
System.out.println("\n\tYou can view your inventory by pressing 'I' or drop an item by pressing 'D'.");
if (locale.item.itemName.equals("map")) {
System.out.println("\n\tTo view the map press 'M'.");
}
//Add the item's worth to the score and set the items worth to zero to prevent double scoring
player1.score += locale.item.value;
System.out.println("\n\t" + locale.item.value + " points have been added to your score.");
System.out.println("\n\tThis is your current score: "+player1.score);
//remove the item from the current location
locale.item = null;
break;
} else {
System.out.println("\n\tThat item is not at this location.");
}
} else {
System.out.println("\n\tThere is no item to pick up here");
}
}//End of Take
This is my Command class:
public class Command {
String command;
String item;
public Command(String comm){
command = comm;
}
public Command(String comm, String item){
this.command = comm;
this.item = item;
}
public void setCommand(String command){
this.command = command;
}
public void setItem(String item){
this.item = item;
}
public String getCommand(){
return this.command;
}
public String getItem(){
return this.item;
}
public String toString(){
return this.command + ":" + this.item;
}
}
These are my items:
//Items {itemName, itemDes}
static Item[] items = {
new Item ("map","a layout of your house", 10 ),
new Item ("battery", "a double A battery", 5),
new Item ("flashlight", "a small silver flashlight", 10),
new Item ("key", "this unlocks some door in your house", 15),
};
I have more code if this is unclear.

My suggestion is to do it the following way:
change
if (userCommand.item.equalsIgnoreCase(locale.item.itemName)) {
to
if (userCommand.item!=null && userCommand.item.equalsIgnoreCase(locale.item.itemName)) {
This is the simplest way, which won't throw an exception if there was no item in the command.
(I'm sorry if this was not your question, but this is the problem what I think you mean.)

Related

How to exit all multiple nested methods at once

I've been following Tim Buchalka's course Java Programming Masterclass for Software Developers and I've been modifying his program from lesson 118.
I want to update my list at the runtime while using the list iterator (navigate method). The program runs fine, but if I update my list, Java throws an error: ConcurrentModificationException
I have come up with the following solution:
Whenever a user performs a modification of the list, other methods run, and update the list and pass it to the navigate() method. By doing this, my program enters multi-level nested methods, and the problem comes up when a user wants to exit from the program (case 0: in navigate() method). User has to press 0 as many times as many nested methods were ran.
My initial idea was to count how many times navigate() was nested, then using for loop return as many times as it was nested. But later I understood it does not make sense
What can I do to exit from the program by using case 0: just once?
package com.practice;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class List extends Traveler {
private LinkedList<String> linkedList;
private String tripName;
public List(String travelerName, int travelerAge, String tripName) {//it has to have same amount of parameters or more with super constructor!
super(travelerName, travelerAge);
this.tripName = tripName;
this.linkedList = new LinkedList<>();
}
public List(){} //it has to have same amount of parameters or more with super constructor!
public LinkedList<String> getLinkedList() {
return linkedList;
}
public String getTripName() {
return tripName;
}
private void removeCity(LinkedList<String> cityList, String deletedCity) {
if(cityList.remove(deletedCity)) {
System.out.println(deletedCity + " has been removed");
} else System.out.println("Could not find the city you want to remove");
List.navigate(cityList);
}
//adds a new city and update the list without an error
private void noExceptionError(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator();
while((listIterator.hasNext())) {
int comparison = listIterator.next().compareTo(cityName);
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous();
break;
}
}
listIterator.add(cityName);
List.navigate(listOfCities);
}
private void loadToList(LinkedList<String> listOfCities) {
alphabeticallyAdd(listOfCities, "Poznan");
alphabeticallyAdd(listOfCities, "Gdansk");
alphabeticallyAdd(listOfCities, "Szczeczin");
alphabeticallyAdd(listOfCities, "Warszawa");
alphabeticallyAdd(listOfCities, "Lodz");
alphabeticallyAdd(listOfCities, "Wroclaw");
List.navigate(listOfCities);
}
private void alphabeticallyAdd(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator(); //just a setup; doesn't point to the 1st element
while((listIterator.hasNext())) {
//if value is greater, the word that is in the list is alphabetically bigger, thus, put it before the list element
//if equal, it is duplicate! return false
// else it is less, thus, we have to move further in the list
int comparison = listIterator.next().compareTo(cityName); //retrieves the 1st value and goes to the next
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous(); //because we've used .next() in the int comparison initialization
listIterator.add(cityName); //don't use linkedList.add because it doesn't know the int comparison, so cannot properly add!!!
return;
}
}
listIterator.add(cityName); //adding at the end of the list
}
public static void navigate(LinkedList<String> listOfCities) {
Scanner userChoice = new Scanner(System.in);
List travelListObject = new List();
ListIterator<String> listIterator = listOfCities.listIterator();
boolean goingForward = true;
while(true) {
Main.menu();
int choice = userChoice.nextInt();
userChoice.nextLine(); //takes care of enter key problem
switch(choice) {
case 0:
System.out.println("Goodbye");
//possible improvement
/* for(int i = 0; i <= List.amountNestedMethods; i++) {
return;
}*/
return;
case 1: //moving forward
if(!goingForward) {
if(listIterator.hasNext()) {
listIterator.next();
}
}
if(listIterator.hasNext()) {
System.out.println(listIterator.next());
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
goingForward = true;
} else {
System.out.println("No more cities in the list");
goingForward = false;
}
break;
case 2: //moving back
if(goingForward) {
if(listIterator.hasPrevious()) {
listIterator.previous();
}
goingForward = false;
}
if(listIterator.hasPrevious()) {
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
System.out.println(listIterator.previous());
} else {
System.out.println("You're at the beginning of the list");
goingForward = true;
}
break;
case 3:
Main.printCities(listOfCities);
break;
case 4:
break;
case 5:
System.out.println("Write new city");
String addedCity = userChoice.next();
travelListObject.noExceptionError(listOfCities, addedCity);
break;
case 6:
System.out.println("Write the city you want to delete");
String deletedCity = userChoice.next();
travelListObject.removeCity(listOfCities, deletedCity);
break;
case 7:
System.out.println("You have been in " + Traveler.getNumberVisitedCities() + " cities in total");
break;
case 9:
travelListObject.loadToList(listOfCities);
break;
default:
System.out.println("Something weird happened. Try to choose an option again");
}
}
}
}
If you want to exit the program you can simply call System.exit(n), where the n is an integer return code (the convention being that code 0 means normal execution and other values indicate some sort of error).

How to use Generics to simplify my Edit Method

In my program, I am trying to create a method that will Edit any property inside of a BaseContact. BaseContact is an abstract class that is extended within a PersonContact and BusinessContact classes. I want to create an edit method that asks the user what property they want to edit, shows them the old value, and then updates with the new value they want. I reuse a lot of code so I was thinking of trying to make another method that will help recycle code, but I'm unsure how that would work with the need of unique getters and setters.
public void editQuery() {
}
// Edit BaseContact
public void edit(int id) {
try {
contacts.contains(contacts.get(id - 1));
} catch (IndexOutOfBoundsException e) {
System.out.println("Contact does not exist\n--- EXIT ---");
return;
}
Boolean active = true;
// While Statement for Edit
while (active) {
System.out.println(
"What property would you like to edit?\n1. Name\n2. Phone Number\n3. Date of Birth\n4. Hobby\n5. Description"
+ "\n6. Website URL\n7. Hours of Operation\n8. Street\n9. City\n10. State\n11. Zip Code\n12. Location"
+ "\n13. Relatives" + "\n14. Photos\n15. Exit");
String choice = sc.nextLine();
switch (choice.toUpperCase()) {
case "1":
case "NAME":
for (BaseContact contact : contacts) {
if (contact.getId() == id) {
System.out.println("Contact Name: " + contact.getName() + "\n");
System.out.print("New Name: ");
String name = sc.nextLine();
contact.setName(name);
System.out.println("Contact Name Set To: " + contact.getName());
}
}
break;
case "3":
case "DATE OF BIRTH":
for (BaseContact contact : contacts) {
if (contact.getId() == id) {
if (contact.getType().equals("personContact")) {
PersonContact temp = (PersonContact) contact;
System.out.println("Contact Date of Birth (ex. January 01, 1999): " + temp.getDob() + "\n");
System.out.print("New Date of Birth: ");
String dob = sc.nextLine();
temp.setDob(dob);
System.out.println("Contact Date of Birth Set To: " + temp.getDob());
}
}
}
break;
case "10":
case "STATE":
for (BaseContact contact : contacts) {
if (contact.getId() == id) {
System.out.println("Contact State: " + contact.getLocation().getState());
System.out.print("New State: ");
String state = sc.nextLine();
contact.getLocation().setState(state);
System.out.println("Contact State Set To: " + contact.getLocation().getState());
}
}
break;
case "12":
case "LOCATION":
for (BaseContact contact : contacts) {
if (contact.getId() == id) {
// Location
Location location = createLocation();
contact.getLocation().setStreet(location.getStreet());
contact.getLocation().setCity(location.getCity());
contact.getLocation().setState(location.getState());
contact.getLocation().setZipCode(location.getZipCode());
System.out.println("Contact Location Set To: " + contact.getLocation());
}
}
break;
case "13":
case "RELATIVES":
for (BaseContact contact : contacts) {
if (contact.getId() == id) {
if (contact.getType().equals("personContact")) {
PersonContact temp = (PersonContact) contact;
System.out.println("List of Relatives");
System.out.print("Contact Relatives: ");
for (int i = 0; i < temp.getRelatives().size(); i++) {
System.out.println(temp.getRelatives().get(i).getName());
}
System.out.println("Would you like to 1. Add or 2. Remove relatives?");
String rChoice = sc.nextLine();
// Adding Relative
if (rChoice.equalsIgnoreCase("1") || rChoice.equalsIgnoreCase("ADD")) {
System.out.println("--- Add Relatives ---");
System.out.println("List of Available Contacts\n");
for (BaseContact rcontact : contacts) {
if (rcontact.getType().equals("personContact")) {
PersonContact rtemp = (PersonContact) rcontact;
System.out.print(rtemp.getName() + " | ");
}
}
System.out.println();
System.out.println("How many relatives would you like to add?");
int numOfRelatives = sc.nextInt();
sc.nextLine();
for (int i = 0; i < numOfRelatives; i++) {
System.out.println("--- Add Relative ---");
System.out.print("Relative Name: ");
String rname = sc.nextLine();
for (BaseContact r2contact : contacts) {
if (r2contact.getType().equals("personContact")) {
PersonContact r2temp = (PersonContact) r2contact;
if (rname.equalsIgnoreCase(r2temp.getName())) {
temp.getRelatives().add(r2temp);
}
}
}
}
// Removing Relative
} else if (rChoice.equals("2") || rChoice.equalsIgnoreCase("REMOVE")) {
System.out.println("--- Remove Relatives ---");
System.out.println("List of Relatives");
for (int i = 0; i < temp.getRelatives().size(); i++) {
System.out.println(temp.getRelatives().get(i).getName());
}
System.out.println();
System.out.println("How many relatives would you like to remove?");
int numOfRelatives = sc.nextInt();
sc.nextLine();
if (numOfRelatives > temp.getRelatives().size()
|| numOfRelatives == temp.getRelatives().size()) {
temp.getRelatives().clear();
System.out.println("All Relatives Removed");
} else {
for (int i = 0; i < numOfRelatives; i++) {
System.out.println("--- Remove Relative ---");
System.out.print("Relative Name: ");
String rName = sc.nextLine();
for (BaseContact r2contact : contacts) {
if (r2contact.getType().equals("personContact")) {
PersonContact r2temp = (PersonContact) r2contact;
if (rName.equalsIgnoreCase(r2temp.getName())) {
temp.getRelatives().remove(r2temp);
}
}
}
}
}
} else {
System.out.println("Invalid Option");
}
}
}
}
break;
Well ask and thou shall receive. I have looked mainly at the humongous switch statement you have going on. For a starter, that should be condensed. A more functional style of programming can help here.
I had to deduce a lot of the classes you have used based on the methods which were called in the code. Furthermore, I have picked a couple of switch expressions and converted them in something more dynamic. See this as a starting point to build on for the rest of your application.
Start of with creating an action class for the simple edits:
public class ActionHolder {
private final String actionText;
private final BiConsumer<String, PersonContact> action;
private final Function<PersonContact, String> originalValFunc;
public ActionHolder(String actionText, BiConsumer<String, PersonContact> action,
Function<PersonContact, String> originalValFunc) {
this.actionText = actionText;
this.action = action;
this.originalValFunc = originalValFunc;
}
public String getActionText() {
return actionText;
}
public BiConsumer<String, PersonContact> getAction() {
return action;
}
public Function<PersonContact, String> getOriginalValFunc() {
return originalValFunc;
}
}
The action class relies heavily on functional interfaces, make sure you read up on them thoroughly as they provide a powerful way of programming. (https://www.baeldung.com/java-8-functional-interfaces)
actionText: Is used to label the attribute which is edited.
action: A function which accepts two arguments and returns nothing.
In this case we will use this to set the respective value on the
PersonContact
originalValFunc: A function to retrieve the origional value from the
PersonContact, it is a function with one parameter (PersonContact)
and it returns a string.
The edit method can then be build up as follows:
class TestInputProgram {
public static void main(String[] args) {
TestInputProgram inputProgram = new TestInputProgram();
inputProgram.edit(1);
}
private final Scanner sc = new Scanner(System.in);
//Initialize with temp data
private final ArrayList<PersonContact> contacts = new ArrayList<PersonContact>() {{
add(new PersonContact(1));
}};
private static final Map<String, ActionHolder> actionMap = new HashMap<String, ActionHolder>() {{
put("1", new ActionHolder("Contact Name",
(input, contact) -> contact.setName(input), BaseContact::getName));
put("NAME", new ActionHolder("Contact Name",
(input, contact) -> contact.setName(input), BaseContact::getName));
put("3", new ActionHolder("Date of Birth",
(input, contact) -> contact.setDob(input), PersonContact::getDob));
put("DATE OF BIRTH", new ActionHolder("Date of Birth",
(input, contact) -> contact.setDob(input), PersonContact::getDob));
put("10", new ActionHolder("State",
(input, contact) -> contact.getLocation().setState(input),
(contact -> contact.getLocation().getState())));
put("STATE", new ActionHolder("State",
(input, contact) -> contact.getLocation().setState(input),
(contact -> contact.getLocation().getState())));
}};
// Edit BaseContact
public void edit(int id) {
while (true) {
System.out.println(
"What property would you like to edit?\n" +
"1. Name\n" +
"2. Phone Number\n" +
"3. Date of Birth\n" +
"15. Exit");
String choice = sc.nextLine();
if (Objects.equals(choice, "15")) {
break;
}
PersonContact pContact = contacts.stream()
.filter(contact -> contact.id == id)
.findFirst()
.orElseThrow(
() -> new IllegalArgumentException("Contact with id: " + id + " does not exist!")
);
Optional.ofNullable(actionMap.get(choice.toUpperCase())).ifPresent(actionHolder -> {
System.out.println(actionHolder.getActionText() + " current value: "
+ actionHolder.getOriginalValFunc().apply(pContact) + "\n");
System.out.println("Please provide the new value:");
String newValue = sc.nextLine();
actionHolder.getAction().accept(newValue, pContact);
System.out.println(actionHolder.getActionText() + " set to: "
+ actionHolder.getOriginalValFunc().apply(pContact));
System.out.println("############################# \n");
});
}
}
}
Some brief info about the variables and whats going on:
The actionMap holds all the possible edit options we currently provide. Notice the implementation of the action holder arguments. We implement the actions using both lamda's and static method references. Inside the edit method the map is queried and the actionHolder retrieved. The respective input action info is then printed to the user and asked for input. The input is processed using the (BiConsumer) from the actionHolder.
I hope this will provide some reference for future programming optimization.

How to remove the brackets from an ArrayList<String>

So I am making a plugin for a Minecraft server and I had to get my command command argument from one class to another and After trying multiple things, I started using an ArrayList, It worked for the most part but it put brackets around
the argument.
ArrayList<String> target = Main.target;
#EventHandler
public void invClickEvent(InventoryClickEvent e) {
Inventory inv = e.getInventory();
Player player = (Player) e.getWhoClicked();
String name = inv.getName();
if ( name.equals(ChatColor.RED + "Ban Menu")) {
e.setCancelled(true);
int slot = e.getSlot();
if (slot < 0)
{
return;
}
if (slot == 0)
{
player.performCommand("kill " + target);
player.closeInventory();
return;
}
That is the code that is giving me troubles. It is pulling the data from my main class. It the ArrayList is pulling text from an argument.
public static ArrayList<String> target = new ArrayList<String>();
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender instanceof Player && args.length == 1)
{
Player p = (Player) sender;
if (args.length > 0) {
switch (args.length)
{
case 1:
Player player = Bukkit.getPlayer(args[0]);
if (player == null) {
sender.sendMessage("That player is not online");
} else if (player.isOnline()) {
Menus.openMenu(p);
target.add(player.getPlayerListName());
}
That is where the array is pulling the argument. The output would be something like player executed command: /kill [HoloPanio] and I want it to output player executed command: /kill HoloPanio
If there is another method to import the arguments please let me know, if not then please tell me how to fix this issue.
Thanks!
Just expanding on what Titus has said in their comment.
Instead of using ArrayList, try using a String as the type for target. This will allow the output to be player executed command: /kill HoloPanio.
String target = Main.target;
#EventHandler
public void invClickEvent(InventoryClickEvent e) {
Inventory inv = e.getInventory();
Player player = (Player) e.getWhoClicked();
String name = inv.getName();
if ( name.equals(ChatColor.RED + "Ban Menu")) {
e.setCancelled(true);
int slot = e.getSlot();
if (slot < 0)
{
return;
}
if (slot == 0)
{
player.performCommand("kill " + target);
player.closeInventory();
return;
}
The below would be updated to initial target as an empty String. Note that a static variable will be updated for every user of this class. This means that any other code accessing this class will have the same target. And, any other code accessing this class can change the target.
public static String target = "";
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender instanceof Player && args.length == 1)
{
Player p = (Player) sender;
if (args.length > 0) {
switch (args.length)
{
case 1:
Player player = Bukkit.getPlayer(args[0]);
if (player == null) {
sender.sendMessage("That player is not online");
} else if (player.isOnline()) {
Menus.openMenu(p);
target = player.getPlayerListName();
}
Also as Titus said, this is not the best solution because, as a static variable, the target will likely change when you don't want it to (or will end up being the same when you want it to change). But, this should solve the command issue.
This is default ArrayList toString.
Use to String.join to remove the brackets
String result = String.join("", list);
This is because of toString method of ArrayList class.
Extends the ArryList class and override the toString
ArrayList<String> list = new ArrayList<String>()
{
private static final long serialVersionUID = 1L;
#Override public String toString()
{
return super.toString().substring(1,super.toString().length-1) ;
}
};
Speaking absolutely nothing to the Minecraft angle, if you wanted to get the list of elements back and not have to print the collection, you could aggregate it with a StringJoiner instead.
String values = String.join(",", target);
System.out.println(values);

Variable returning value of previously entered element in java arraylist

I'm trying create a program that use dialog boxes and stores elements in Object Goals(string, int, int). This is just a home project I've decided to do during Uni holidays.
So far it's working how I planned but there is one bug I can't figure out.
//asks user to input goals and stores them in an array list
public static void setup(){
int n = 0;
int i = 0;
boolean setupFinished = false;
boolean success = false;
List<Goals> setupList = new ArrayList<Goals>();
JOptionPane setupBox = new JOptionPane();
while(!setupFinished){
Goals goal = new Goals();
String str1 = JOptionPane.showInputDialog("A goal you wish to work on?");
if(str1 == null){
System.exit(0);
}
goal.setGoal(str1);
String goalPrefInput = JOptionPane.showInputDialog("What is the initial preference of this goal compare to the others?");
if(goalPrefInput == null){
System.exit(0);
} else if (goalPrefInput.equalsIgnoreCase("")){
n = Integer.parseInt("1");
} else {
while(!success){
try {
n = (Integer.parseInt(goalPrefInput));
success = true;
}
catch (Exception NumberFormatException){
JOptionPane.showMessageDialog(null, "You must enter a valid number");
}
}
}
goal.setGoalPref(n);
System.out.println(goal.getGoalPref());
success = false;
String goalFreqInput = JOptionPane.showInputDialog("What is the frequency rate you wish this preference to increase?");
if(goalFreqInput == null){
System.exit(0);
} else if (goalFreqInput.equalsIgnoreCase("")){
n = Integer.parseInt("1");
} else {
while(!success){
try {
n = (Integer.parseInt(goalFreqInput));
success = true;
}
catch (Exception NumberFormatException){
JOptionPane.showMessageDialog(null, "You must enter a valid number");
}
}
}
goal.setGoalPrefIncrease(n);
System.out.println(goal.getGoalPrefIncrease());
setupList.add(i, goal);
i++;
int f = JOptionPane.showConfirmDialog(null, "Have you finished setup?", "Setup Finished?", YES_NO_OPTION);
if(f == JOptionPane.YES_OPTION){
setupFinished = true;
}
}
System.out.print(setupList.toString());
String s = removeBrackets(setupList.toString());
JOptionPane.showMessageDialog(setupBox, "Here are your goals \n" + s);
}
}
It's not finished but what is happening that I don't understand is that the user will enter the first instance of goal the user will put in -
goal: a, goalPref: 1, goalFreq: 1.
Then the second instance they will put in
goal: b, goalPref: 2, goalFreq: 2.
However for the second instance the goalPref that is suppose to 2 will return 1 whilst goalFreq will return a 2 correctly. If the next instance is
goal: c, goalPref: 3 goalFreq: 3.
Then it will return c, 2, 3 as the previous goalPref was 2.
The thing that confuses me is the code for entering goalPref and goalFreq is identical so why is one working and one isn't?
Here is the Goals class code:
public class Goals {
private String goal;
private int goalPref;
private int goalPrefIncrease;
public String getGoal() {
return goal;
}
public void setGoal(String goal) {
this.goal = goal;
}
public int getGoalPref() {
return goalPref;
}
public void setGoalPref(int goalPref) {
this.goalPref = goalPref;
}
public int getGoalPrefIncrease() {
return goalPrefIncrease;
}
public void setGoalPrefIncrease(int goalPrefIncrease) {
this.goalPrefIncrease = goalPrefIncrease;
}
#Override
public String toString() {
String s = "Goal: " + this.getGoal() + ", Goal Preference: " + this.getGoalPref() + ", Goal Frequency Rate: " + this.getGoalPrefIncrease();
//String s = goal + ", Goal Preference: " + goalPref + ", Goal Frequency Rate: " + goalPrefIncrease;
return s;
}
}
You should have used a debugger to see what is the mistake in your code. The problem here is your success variable which holds a key in determining value of n for your inputs.
Currently at the end of your loop it is true so in next cycle its value is still true and after entering goal pref it is not going in your while(!success) loop to determine value of n so last value of n(which is last value of goal frequency you entered) is assigned to new goal pref.
In order to correct it you need to reset value of success to false at the start of every iteration.
while(!setupFinished){
success = false;
Goals goal = new Goals();
Hope this helps.

How do i compare a variable's data with the data in an ArrayList?

I am calling a method that passes in a variable. I want to be able to compare this variable to all the items in an ArrayList to see if there is a match.
This is my code...
private boolean input;
private ArrayList chcekItem = new ArrayList();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
}
else {
Iterator iterators = getChcekItem().iterator();
while (iterators.hasNext()) {
if (iterators.next()==action) {
System.out.println(iterators.next()+"="+action);
input=false;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}
else{
System.out.println("The item " + action + " is Exist");
}
}
}
My code isn't working as I had expected. Could someone please help me fix the problem.
I take it that the checkItem variable is a List of Strings, thus it should be defined like this:
private List<String> checkItem = new ArrayList<String>();
When comparing an String you don't use string1==string2 but string1.equals(string2);
So
(iterators.next()==action)
should be:
(iterators.next().equals(action))
Remember to check the string for null values.
So the whole code could look like this:
private boolean input;
private List<String> chcekItem= new ArrayList<String>();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
} else {
//Foreach loop instead of an iterator ;)
for(String item : chcekItem) {
if(item.equals(action)) {
System.out.println(item+"="+action);
input=false;
//We can jump out of the loop here since we already found a matching value
break;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}else{
System.out.println("The item " + action + " is Exist");
}
}
}
}

Categories

Resources