loop to check string array for item - java

I have this array
public static ArrayList<String> inventory = new ArrayList<String>();
and have the players items stored inside of it.
I want to add a feature in the shop class that will sell everything but the pickaxe, how can I create a loop to check if theres something in the array other than "pickaxe" and if there is to remove it?
To remove I have a void
public void removeAllInventory() {
inventory.clear();
}
or
public void removeInventory(String item) {
inventory.remove(item);
}
Could I just edit the removeAllInventory to ignore the pickaxe and make a new void called removeAllShop or something? If so what would go in that void?
This is where I need to put it in:
else if (input.input.equalsIgnoreCase("all")) {
}

Loop over the list, check if if each element is equal to pickaxe, and remove it if it not.
Iterator<String> i = inventory.iterator();
while (i.hasNext()) {
if (i.next().equalsIgnoreCase("pickaxe"))
i.remove()
}

You shouldn't edit removeAllInventory() to remove everything but the pickaxe. Its name would no longer make sense, and it seems a reasonable routine to keep around.
But you could add a new method, removeAllInventoryExcept(String item), that removes everything but the given the item.
Hope this helps.
EDIT: In attempt to beef up this answer, I'd also like to suggest the "out of the box" solution of:
public void removeAllInventoryExcept(String item) {
ArrayList<String> newInv = new ArrayList<String>();
newInv.add(item);
inventory = newInv;
}
This avoids the costly iteration and string comparisons.

I'm assuming all of the items in the inventory are an ancestor of an item class, and not just a String.
You could loop through the ArrayList, getting the names of each element and comparing it with the pickaxe name.
or
You could loop through the ArrayList and checking if each item is an instanceof
pickaxe, and if it is not, remove it from the ArrayList
edit* It seems you specified the ArrayList is of type String, so ignore the second option

for (String item : inventory) {
if (!"pixckaxe".equalsIgnoreCase(item)) {
inventory.remove(item);
}
}

Related

How to add another linked list objects

I a homework where I need to merge two linkedlist, "songs" list and "artists" linked list, it works on the first list the "song" list, but whenever i add another list it just wont work
as you can see here the public static void now has errors
package mergedlinkedlist;
import java.util.LinkedList;
public class Mergedlinkedlist {
public static void main(String[] args) {
LinkedList<String>song = new LinkedList<>();
song.add("imagine");
song.add("bohemian rhapsody");
song.add("highway to hell");
System.out.println(song);
}
public static void main(String[] args) {
LinkedList<String>artists = new LinkedList<>();
artists.add("john lennon");
artists.add("queen");
artists.add("ACDC");
System.out.println(artists);
}
Okey, as one comment has pointed out, no program can have 2 main methods. You cannot create another one.
I suggest to integrate the code from your second into your first. You can safely just add the contents together.
The task is to merge the lists. Do you need any more help with that?
Assuming the task says you know the size of the list you can just create a new list and use the same method you used above to add them to the list. If you do not, you will need to use a loop. It would look like this:
LinkedList<String>artistsAndSongs = new LinkedList<>();
if (artists.size() == songs.size()) {
for (int i = 0; i < artists.size(); i++) {
artistsAndSongs.add(artists.get(i));
artistsAndSongs.add(songs.get(i));
}
} else {
System.out.println("Not every artist is matched with a song!");
}
But you should read up on how linked lists work exactly in the documentation. This will not only improve your understanding of the class but also teach you how to quickly find solutions to your problem.
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Making all values in an array unique

Im making a small school project, keep in mind i'm a beginner. Im gonna make a small system that adds member numbers of members at a gym to an array. I need to make sure that people cant get the same member number, in other words make sure the same value doesnt appear on serveral index spots.
So far my method looks like this:
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
if(memberNr.equals(mNr)){
throw new IllegalArgumentException("The member is already in the system");
}
else{
memberNr[count++] = mNr;
}
}
While having a contructor and some attributes like this:
int[] memberNr;
int arraySize;
int count;
public TrainingList(int arraySize){
this.arraySize = arraySize;
this.memberNr = new int[arraySize];
}
As you can see i tried using equals, which doesnt seem to work.. But honestly i have no idea how to make each value unique
I hope some of you can help me out
Thanks alot
You can use set in java
Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
mport java.util.*;
public class Set_example
{
public static void main(String[] args)
{
// Set deonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("a");
hash_Set.add("b");
hash_Set.add("a");
hash_Set.add("c");
hash_Set.add("d");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
// Set deonstration using TreeSet
System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
}
}
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
//You need to loop through your array and throw exception if the incoming value mNr already present
for(int i=0; i<memberNr.length; i++){
if(memberNr[i] == mNr){
throw new IllegalArgumentException("The member is already in the system");
}
}
//Otherwise just add it
memberNr[count++] = mNr;
}
I hope the comments added inline explains the code. Let me know how this goes.
Hey you can’t directly comparing arrays (collection of values with one integer value)
First iterate the element in membernr and check with the integer value

Java ArrayList trying to check if object with this name exists

I'm having a bit of trouble in my head trying to solve this:
I'm working on a "rankList", an arrayList made of "Score". Score it's the object that has the following atributes: name,wins,loses,draws. My class Ranking has an ArrayList of Score objects. To create a new Score object I just use the name (and set the rest to 0 since it's new). However I'm trying to check if the player's name it's already in rankList I don't have to create new but sum a win or lose or draw.
I have been reading arround that I have to override equals then others say I have to override contains... It's getting a big mess in my head. My fastest solution would be to write an "for" that goes arround the arrayList and use the getName().equals("name"); however this is getting too messi in my code. I have checkPlayer (if the palyer is in the list):
public boolean checkPlayer(String playerName) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
return true;
}
}
return false;
}
then if I want to incrase the wins i have this :
public void incraseWins(String playerName) {
if (checkPlayer(playerName)) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
} else {
createPlayer(playerName);
//more for to get to the player i'm looking for...
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
}
So i guess there is a better way to do this... :/
ArrayList is not the right data structure here. To check if an element exists in the array you are searching the entire arraylist. Which means it's O(N).
To keep an array list is sorted order and do a binary search on it would definitely be faster as suggested in the comments. But that wouldn't solve all your problems either because insert into the middle would be slow. Please see this Q&A: When to use LinkedList over ArrayList?
One suggestion is to use a Map. You would then be storing player name, player object pairs. This would give you very quick look ups. Worst case is O(log N) i believe.
It's also worth mentioning that you would probably need to make a permanent record of these scores eventually. If so an indexed RDBMS would give you much better performance and make your code a lot simpler.
Try using a hashtable with a key, it would be much more efficient!
e..Why not using map<>.
a binary search is good idea if you must use List,code like this
List<Method> a= new ArrayList<>();
//some method data add...
int index = Collections.binarySearch(a, m);
Method f = a.get(index);
and class method is impl of Comparable,then override compareTo() method
public class Method implements Comparable<Method>{
........
#Override
public int compareTo(Method o) {
return this.methodName.compareTo(o.getMethodName());
}
if you don't want use binsearch,CollectionUtils in commons can help you
CollectionUtils.find(a, new Predicate() {
#Override
public boolean evaluate(Object object) {
return ((Method)object).getMethodName().equals("aaa");
}
});
in fact CollectionUtils.find is also a 'for'
for (Iterator iter = collection.iterator(); iter.hasNext();) {
Object item = iter.next();
if (predicate.evaluate(item)) {
return item;
}
}

Searching Arraylists with instanceof for a user query JAVA

The searchDatabase method will accept a query string and search the ArrayList to see if the object contains the query(your search should be case-insensitive!) as the name or is of that object type (Hint: use instanceof to check for object type). It will return an ArrayList containing all of the values whose objects contain the query string.
I need to see if the query is the same as a class name (Such as Don/Talent/Overseer) and if it is then I print all objects of that type. If it's equal to a name in one of the objects then I just print that object out. I am confused as to what to do from here. I am looping through all goons in the Database and checking if they are instances of Don/Overseer/Talents and if they are then checking if the user query is equal to the object type and if it is print all of those objects but if it isn't then checking if it's equal to the name of any objects of type "Dom" in the arraylist.
protected ArrayList<Goon> searchDatabase(String query)
{
ArrayList<Goon> clone = new ArrayList<Goon>();
for(Goon a : goonDB)
{
if(a instanceof Don)
{
if(query.equalsIgnoreCase("don"))
{
}
else
{
if(a.getName().equals(query))
{
}
}
}
else if(a instanceof Overseer)
{
}
Your problem statement is ambiguous, here are my assumptions:
Goon is a parent class of Don/Talent/Overseer (They extend/implement
it).
You accept a query which stands for either object or a name
property in one of the implementation classes.
If query is a type name: return all objects of that type in a list.
Otherwise, check if it matches a name property: return all objects that have the same name property. (Although you said print that one object, I am going to ignore that, because then I would be returning null and more requirement questions arise)
I don't want to write it the code for you, because this looks like a homework assignment and you are much better off struggling a bit, but here is a logic that you would need to use to follow above assumptions:
I would first check if query is Don/Talent/Overseer. If it is then go through the list and add all objects that are of that type (instanceof) to your clone list . If it isn't, then go through the whole list and add those that have the name matching the query. Return the list.
Although I see you've already figured it out. I still want to post my answer :P (or else I made it for nothing). Maybe others who have the same problem can use it. I asumed that Don and Overseer implemented Goon by the way. And as a solution I just looped over the database checking if the query and the class name matched.
I also added a little main method to test the search code. And as you can see in the output only the Don's are printed.
package stackoverflow.question_26510341;
import java.util.ArrayList;
import java.util.Iterator;
public class Search {
static ArrayList<Goon> goonDB = new ArrayList<Goon>();
public static void main(String[] args){
goonDB.add(new Don());
goonDB.add(new Don());
goonDB.add(new Overseer());
ArrayList<Goon> list = searchDatabase("Don");
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
protected static ArrayList<Goon> searchDatabase(String query){
ArrayList<Goon> clone = new ArrayList<Goon>();
Iterator<Goon> iterator = goonDB.iterator();
Goon temp;
while(iterator.hasNext()){
if(query.equals("Don") && (temp = iterator.next()) instanceof Don){
clone.add(temp);
}else if(query.equals("Overseer") && (temp = iterator.next()) instanceof Overseer){
clone.add(temp);
}//etc...
}
return clone;
}
private static interface Goon{
}
private static class Overseer implements Goon{
}
private static class Don implements Goon{
}
}

Delete object from array

I've got this constructor in the class Music:
protected String Title;
protected String Autor;
protected String Type;
protected int Code;
public Music (String title, String autor, String type, int code){
this.setTitle(title);
this.setAutor(autor);
this.setType(type);
this.setCode(code);
}
#Override
public String toString(){
return this.Title + " " + this.Autor + " " + this.Type + " " + this.Code;
}
Then, in other class called ManageMusic I create some methods to then use them on the main class. I also define a String array refered to the Music class which I will use in the main class:
private final Music[] musicList;
private int counter;
public ManageMusic(int maxSize) {
musicList= new Music[maxSize];
counter= 0;
public void add(Music m){
musicList[counter] = m;
counter++;
}
Here, I have to create a delete method which would delete a especific object from the musicList and return this list without that object.
This is the way I add music elements to the musicList on the main class:
static ManageMusic musiclist = new ManageMusic(20);
musicList.add(new Music(title, autor, format, code));
My approach for the delete method in the ManageMusic class is to copy this list into a new String[] and then copy it back to the list. But as I'm using an objet from Music instead of from String, I cannot make the copy back because it does not cast the String to the musicList:
public void delete(int code){
String[] newString = new String[musicList.length];
int index_1 = 0;
for (int i=0; i<musicList.length; i++){
if(i != code){
newString[index_1] = musicList[i].toString();
index_1++;
}
}
int index_2 = 0;
for (int i=0; i<newString.length; i++){ //THIS IS WHERE IT SAYS: Cannot convert
// from String to Music
musicList[index_2] = newString[i];
index_2++;
}
}
I have to do something not far from this, because then I've got a method that list elements from the musicList, so I cannot set a return statement for the method.
Why you can do it without an ArrayList
As some people suggested in the comments, you should probably use ArrayLists or similar stuff from the java.util.collection package.
However I assume you want to learn how such things work, so I will not provide you with code (First because I'm too lazy, second to encourage you to learn it yourself) but with some explanation.
edit: First: Your problem is that you copy strings, not references. Instead of trying to use the toString method, try to handle it with the "objects" (i.e. their references) themselves.
Error checking
As you might have noticed your add will cause an IndexOutOfBoundsException if you try to add another entry after your list reached your max_size. You should check for that. You should also check lots of things in the following explanations, I'll provide a few suggestions.
Simple deletion with your exact example
Just use Music[] instead of String[] and copy the reference of the temp Music[] to your musicList.
Better way to handle it: dynamic array structure
So what I suggest is to make use of a dynamic array structure. You will have to copy arrays around a lot, which can be a bit difficult. But basically it's what an ArrayList does.
Constructor
But how to implement that dynamic structure? Let's first start with the initialization, i.e. your constructor. You will not need a parameter for a maximum size (unless you want to restrict your music collection for some reason). Just create an array with size 0. (Of course you can also implement copy constructors and other things, but for the start keep it simple.)
add()
To add more music, you simply create a new array with the size of your current collection + 1, copy all references (this is probably the answer you were looking for. You take the strings, but just take the objects themselves) from the current array to the new array, add the new Music and change the reference of your member variable to your newly created, bigger array (i.e. assigning musicList = tempArray; or something similar). (Error checking: is the object null?)
delete()
For deletion you can do just the same. Create a new temporary array (this time with a reduced size), copy all values over but leave out the one you want to delete. To determine which shall be deleted you can either check for indices or even check the objects for equality. (Error checking: size of temp array should never be smaller than 1, so check if your array is empty - consider to use a method like isEmpty() for that.)
Why should I do this?
Once you got those concepts you will be able to manage your array in whatever way you like. Search through it, delete all elements, copy your music collection to your friend's, etc. etc.
And beyond that?
And after you learned this, go ahead and try the ArrayList - you will figure out it works very much like what you have just written. And now you can be proud that you not only can use ArrayLists, but also know how and why they behave like they do.
Its better to use ArrayList than writing own logic to delete object from existing array. Here is how you can use ArrayList :
{
ArrayList<Music> list = new ArrayList<Music>();
Music m1 = new Music(title, autor, format, code);
list.add(m1);
// similarly you can check whether object is present in ArrayList or not using
if(list.contains(m1)){ // This check whether object is present in ArrayList or not
//Do whatever you want
}
}
ArrayList example:
List<Music> musicList = new ArrayList<Music>();
adding to end of list list:
musicList.add(new Music(...));
adding to specified position in list (later ones all move up one place)
musicList.add(index, new Music(..));
remove from list:
musicList.remove(index);
or
musicList.remove(someMusic);
Size of list:
int size = musicList.size();
Get first music:
Music first = musicList.get(0);
Get last music:
Music last = musicList.get(musicList.size()-1);
Loop:
for (Music : musicList) {
//do stuff
}
do like this
public void delete(int code){
List<Music> list = new ArrayList<Music>(); //creating new empty list
for (Music m:musicList){
if(m.code != code){ // removing condition
list.add(m); // adding music to new list
}
}
musicList = list.toArray(new Music[list.size()]); // assigning back list to musicList
}

Categories