For my project I need to add a Creature into an array of creatures thats created in a room
public class Room
{
String name;
String description;
String state;
Creature [] creatures = new Creature[10];
public Room(String roomName)
{
name = roomName;
}
public String toString()
{
String retValue = "";
for (int i = 0; i < creatures.length; i++) {
retValue = retValue + creatures[i].toString();
}
return retValue;
}
public void addCreature(String creatureName)
{
for (int i = 0; i < creatures.length; i++)
{
if(creatures[i] == null)
{
creatures[i] = new Creature(creatureName);
}
}
}
}
when I do this, it overwrites the entire array, what can I do to add a single creature to the array?
Use break statement.
if(creatures[i] == null)
{
creatures[i] = new Creature(creatureName);
break;
}
Arrays have only a fixed size. When you write new Creatures[10], it means that your creatures array has at maximum 10 elements inside of it.
You can add items in two different ways:
You can copy the array and make it bigger, and then add the item
You can use ArrayList, which is a class which automatically does #1 for you
I would recommend ArrayList:
ArrayList:
List<Creature> creatures = new ArrayList<>();
public void addCreature(String creatureName) {
creatures.add(new Creature(creatureName));
}
Seems you miss one condition in if clause. I guess it should be
if(current == null || current.getCreatureName() == null) {
creatures[i] = new Creature(creatureName);
}
Related
So I'm currently working on a project that is recreating methods for Array String Lists and Linked String Lists. There is a StringList interface, that both ArrayStringList and LinkedStringList implement. We are not allowed to see the source code for the interface - only the API documentation. For each class, we have to create a default constructor and copy constructor for both classes. I've ran tests, and the default constructors both pass but the ArrayStringList copy constructor does not work and has been throwing the error message of "null" or "-1". I am pretty new to inheritance and interfaces, and I think the object parameters vs string array data types are throwing me off a bit.
Here is the code I have so far, and the methods used in the constructor:
My Copy Constructor:
private String[] stringArray;
private int size;
public ArrayStringList(StringList sl) {
size = sl.size();
ArrayStringList asl = new ArrayStringList();
for(int i = 0; i < size-1; i++) {
if(sl.get(i) != null) {
asl.set(i,sl.get(i).toString());
} //if
} // for
} // copy constructor
Size Method:
public int size() {
return stringArray.length;
} // size
Get Method:
public String get(int index) {
if(index < 0 || index >= size) {
throw new IndexOutOfBoundsException("out of bounds");
} else {
return stringArray[index];
}
} //get
Set Method:
public String set(int index, String s) {
String old = stringArray[index];
stringArray[index] = s;
return old;
} // set
In the project, the description of the copy constructor was as follows:
The implementing class must explicitly define a copy constructor. The copy constructor should take exactly one parameter of the interface type StringList. It should make the newly constructed list object a deep copy of the list referred to by the constructor's parameter. Therefore, the initial size and string elements of the new list object will be the same as the other list. To be clear, the other list can be an object of any implementation of the StringList interface. No other assumptions about the type of the object should be made.
public class ArrayStringList implements StringList {
private static final int INITIAL_CAPACITY = 10;
private String[] stringArray;
private int size;
public ArrayStringList(StringList sl) {
stringArray = sl.toArray();
size = stringArray.length;
}
public ArrayStringList() {
stringArray = new String[INITIAL_CAPACITY];
size = 0;
}
// TODO: Extract 'if-cascade' to an validate(..) method
#Override
public String set(int index, String s) {
if (index >= size) {
throw new IndexOutOfBoundsException("")
} else if (s == null) {
throw new NullPointerException("the specified string is null");
} else if (s.isEmpty()) {
throw new IllegalArgumentException("specified string is empty");
}
String old = stringArray[index];
stringArray[index] = s;
return old;
}
// TODO: Check if posible to extend the stringArray
#Override
public boolean add(String s) {
if (s == null) {
throw new NullPointerException("the specified string is null");
} else if (s.isEmpty()) {
throw new IllegalArgumentException("specified string is empty");
}
if (size == stringArray.length) {
int newListCapacity = stringArray.length * 2;
stringArray = Arrays.copyOf(stringArray, newListCapacity);
}
stringArray[++size] = s;
return true;
}
// TODO: implement other methods ...
}
Keep in mind that this implementation is still buggy, but you can use it as a starting point
public void ArrayStringList(StringList sl) {
size = sl.size();
ArrayStringList asl = new ArrayStringList();
for(int i = 0; i < size; i++) {
if(sl.get(i) != null) {
String s = asl.set(i,sl.get(i).toString());
System.out.println(s);
} //if
} // for
}
Change set method like below. And call it by the help of class object. it will set value in global static list.
//Change set method like this
public String set(int index, String s) {
stringArray[index] = s;
return stringArray[index];
}
I would initialise the internal array to the value of size and also make use of the fact that the String class also has a copy-constructor
public ArrayStringList(StringList sl) {
this.size = sl.size();
this.stringArray = new String[size];
for(int j = 0; j < size; j++) {
this.stringArray[j] = new String(sl.get(i));
}
}
I have two Arraylist.
ArrayList workerlist and Arraylist workernamelist
public class Workers {
private String worker_id;
private String worker_name;
public String getWorker_id() {
return worker_id;
}
public void setWorker_id(String worker_id) {
this.worker_id = worker_id;
}
public String getWorker_name() {
return worker_name;
}
public void setWorker_name(String worker_name) {
this.worker_name = worker_name;
}
}
The Arraylist workernamelist list contains all the worker name in strings.
I want to search through the ArrayList workerlist weather it contains the wokrername in workerlist if it matches with the worker name then it will return corresponding worker id .
I think we only need to traversal the whole workers list, and for each worker, compare it's name with the given worker_name, if they're equal, return the worker's id. If such worker does not exist or the worker_name is null you can return null.
public String findWorkerId(ArrayList<Workers> workerList, String workerName) {
if (workerList == null || workerName == null) {
return null;
}
for (Workers worker : workerList) {
if (workerName.equals(worker.getWorker_name())) {
return worker.getWorker_id();
}
}
return null;
}
public Workers searchWorkers(ArrayList workers,String worker_name){
int len = workers.size();
for(int i = 0; i<len; i++){
your logic
enter code here
}
}
you need a for loop to look through the array list then if any match do display the match or whatever you want to do.
for(int i =0: i< workernamelist.size(); i++){
if(workernamelist.worker_ID = worker_ID){
system.out.println(workerlist.worker_ID);
}
}
Try this,
public String searchs(ArrayList list_workers,String worker_name){
for(int i = 0; i<list_workers.size(); i++){
if(list_workers.get(i).getWorker_name.equals(worker_name)
{
String worker_id=list_workers.get(i).getWorker_id();
Log.d("TAG","worker_id:"+worker_id);
return worker_id;
}
}
return null;
}
You can do something like this:
ArrayList<String> workernamelist=new ArrayList<>();
ArrayList<Workers> workersArrayList=new ArrayList<>();
for(int i=0;i<workernamelist.size();i++)
{
for(int j=0;j<workersArrayList.size();j++) {
if (workernamelist.get(i).equalsIgnoreCase(workersArrayList.get(j).getWorker_name()))
{
String id=workersArrayList.get(j).getWorker_id();
}
}
}
I was attempting to write some code for a program in BlueJ (Java) that lists bags and adds and removes items from those bags, that sort of thing. Then I got stuck in the first class; I couldn't get to add an item to the bag properly as you can notice below in the addItem() method; it keeps adding String s to every null element in the array rather the first encountered. Any help would be tremendously appreciated.
Best wishes & many thanks,
Xenos
public class Bag1 {
private String[] store; // This is an array holding mutlitple strings.
public Bag1(int storageCapacity) {
store = new String[storageCapacity];
} // That was the primitive array constructor.
public boolean isFull() {
boolean full = true;
for(int i = 0; i < store.length; i++) {
if(store[i] == null) {
full = false;
}
}
return full;
} // The method above checks if the bag is full or not, and returns a boolean value on that basis.
public void add(String s) {
for(int i = store.length; i >= 0; i--) {
if(store[i] == null) {
store[i] = s;
}
}
}
}
You should exit the loop after finding the first empty spot :
public void add(String s)
{
for(int i=store.length-1; i>=0; i--) { // note the change in the starting index
if(store[i]==null) {
store[i] = s;
break;
}
}
}
I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.
I ran into a bind whereby I had to sort the data read from the phones PIM. In doing this I lost the other to which each contact field was referenced to the telephone number because I made use of 2 separate vectors as illustrated below
Before sorting
Nna - +445535533
Ex - +373773737
Ab - +234575757
After sorting.(Which shouldn't be)
Ab - +445535533
Ex - +373773737
Nna - +234575757
This gives an undesired behavior since the sort removes the index to index pointer of the vectors and a selected name (in a Multiple list Box) will get a wrong number.
Alternatively,
I used a hashtable, with the intention of using the names as keys and numbers as the values.
But this pairing means duplicate names being used as keys will not be allowed. Thus I made it a i.e the phone number as keys instead.
I don't want to sound like a cry baby so I stop here for a while and so you the code with a hope u guys would understand it
MY QUESTION
1. Is there a better way/algorithm to implement this?
2. How do I implement the getSelectedItems() in such a ways that it grabs the numbers of the selected indexes of a MULTIPLE CHOICE LIST from a hashTable
import java.util.Enumeration;
import java.util.Vector;
import java.util.Hashtable;
import javax.microedition.lcdui.List;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;
/**
*
* #author nnanna
*/
public class LoadContacts implements Operation {
private boolean available;
private Vector telNames = new Vector();
Vector telNumbers = new Vector();
Hashtable Listcontact = new Hashtable();
private String[] names;
public Vector getTelNames() {
return telNames;
}
public Hashtable getListcontact() {
return Listcontact;
}
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute()");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME) && contactList.isSupportedField(Contact.TEL)) {
Enumeration items = contactList.items();
Hashtable temp = new Hashtable();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone availableContacts
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
Listcontact.put(telNumber, contactName);
temp.put(contactName, telNumber);
}
names = getSortedList();
// Listcontact = temp;
System.out.println(temp + "-------");
System.out.println(Listcontact + "*******");
shortenName(contactName, 20);
}
available = true;
}
} else {
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}
private void shortenName(String name, int length) {
if (name.length() > length) {
name = name.substring(0, 17) + "...";
}
}
public Vector getSelectedItems(List lbx) {
boolean[] arrSel = new boolean[lbx.size()];
Vector selectedNumbers = new Vector();
int selected = lbx.getSelectedFlags(arrSel);
String selectedString;
String result = "";
for (int i = 0; i < arrSel.length; i++) {
if (arrSel[i]) {
selectedString = lbx.getString(lbx.getSelectedFlags(arrSel));
result = result + " " + i;
System.out.println(Listcontact.get(selectedString));
// System.out.println(telNumbers.elementAt(i));
}
}
return selectedNumbers;
}
private String[] sortResults(String data[]) {
RecordSorter sorter = new RecordSorter();
boolean changed = true;
while (changed) {
changed = false;
for (int j = 0; j < (data.length - 1); j++) {
String a = data[j], b = data[j + 1];
if (a != null && b != null) {
int order = sorter.compare(a.getBytes(), b.getBytes());
if (order == RecordSorter.FOLLOWS) {
changed = true;
data[j] = b;
data[j + 1] = a;
}
}
}
}
return data;
}
public String[] getNames() {
return names;
}
Vector elements = new Vector();
private String[] getValueArray(Hashtable value) {
System.out.println(Listcontact + " c");
Enumeration e = value.elements();
while (e.hasMoreElements()) {
elements.addElement(e.nextElement());
}
String[] elementsArray = new String[elements.size()];
elements.copyInto(elementsArray);
elements.removeAllElements();
System.out.println(elementsArray + " k");
return elementsArray;
}
public void getDuplicates(Vector realValue) {
Vector duplicate = new Vector();
Enumeration e = realValue.elements();
for (int i = 0; e.hasMoreElements(); i++) {
if (duplicate.isEmpty() || !duplicate.elementAt(i).equals(e.nextElement())) {
break;
} else {
duplicate.addElement(e.nextElement());
}
}
}
public String[] getSortedList() {
return sortResults(getValueArray(Listcontact));
}
}
Let me reiterate you requirement: You want a method that will sort the contacts read from native phonebook, then alphabetically sort them on name.
Following is the approach,
Replace the vectors and hash-tables in your code with a single vector, say contactListVector, containing elements of type ContactItem, don't worry this class is explained below. Fundamentally the contact's name and number(s) are linked together in a ContactItem, hence you do not have to worry about there mappings which reduces the usage of redundant data structures.
class ContactItem {
private String name;
private String tnumber; //this can also be a data structure
//for storing multiple numbers
ContactItem( String name, String tnumber) {
this.name = name;
this.tnumber = tnumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTnumber() {
return tnumber;
}
public void setTnumber(String tnumber) {
this.tnumber = tnumber;
}
}
You can reuse the sorting algorithm on contactListVector by comparing the member variable ContactItem.name of the vector element. Also you can deploy different sorts on member variables numbers and/or names. Also there are lots of libraries for JavaME available that have better sorting algorithm's implemented if need be use them.
I would recommend you to perform the sorting once on the contactListVector elements at the end of your method loadNames(...) maybe in the finally block triggered by some boolean variable. The current sorting call in each iteration on items enumeration is expensive and time consuming.
Also you can serialize / deserialize the ContactItem thus persist your contact list.
Let me know if you need detailed explanation.
What about inserting the contact name and numbers inside a recordStore , so you can later make a sort by creating a class which implements RecordComparator.
This statement in your code makes no sense:
selectedString = lbx.getString(lbx.getSelectedFlags(arrSel))
Per lcdui List API documentation above will return the string located at the index equal to the number of selected elements why would you need that?
If you need to output selected text for debugging purposes, use lbx.getString(i) instead.
To implement the getSelectedItems() in such a ways that it grabs the numbers of the selected indexes of a MULTIPLE CHOICE LIST do about as follows:
public Vector getSelectedItems(List lbx) {
boolean[] arrSel = new boolean[lbx.size()];
Vector selectedNumbers = new Vector();
int selected = lbx.getSelectedFlags(arrSel);
System.out.println("selected: [" + selected + "] elements in list");
String selectedString;
String result = "";
for (int i = 0; i < arrSel.length; i++) {
if (arrSel[i]) {
// here, i is the selected index
selectedNumbers.addElement(new Integer(i)); // add i to result
String selectedString = lbx.getString(i);
System.out.println("selected [" + selectedString
+ "] text at index: [" + i + "]");
}
}
return selectedNumbers;
}
As for sorting needs, just drop the HashTable and use Vector of properly designed objects instead as suggested in another answer - with your own sorting algorithm or one from some 3rd party J2ME library.
I would suggest you to have Contact class with name and Vector of numbers. And instead of sorting names array sort the array of contacts.