I was wondering how do I go about to create 2 methods,
1. Which does the checking, if the object already exists within the array (based on one of the parameters).
2. Secondly add a method which allows the user / me to add objects into the array when the previous (1st method) returns false.
Here is my try:
public class Book {
String name;
int isbn;
public Book(String e, int iNr) throws LibraryException{
if(e.equals("")){
throw new LibraryException("Blank / empty name is not allowed!");
}
else if(iNr < 1 || iNr > 9000){
throw new LibraryException("The isbn number is outside the allowed range (1 - 9000)! ");
}
setName(e);
setIsbn(iNr);
}
public boolean equals(Object obj){
if(obj instanceof Book){
isbn = (isbn)obj;
return true;
}
return false;
}
public String getName() {
if(name == null || name == ""){
System.out.print("Does not exist!");
}
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIsbn() {
if(isbn < 0){
System.out.print("ISBN (LIBRI) EXCEPTION TO BE ADDED!");
}
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
}
.
public class Library
{
String name;
Book[] books;
int nrBooks = 0;
public Library(String name, int nrBooks) throws LibraryException {
if(name.equals("")){
throw new LibraryException("Blank names is not allowed");
}
if(nrBooks < 500){
throw new LibraryException("The number of books needs to be greater than 500!");
}
this.name = name;
this.nrBooks = nrBooks;
this.books = new Book[nrBooks];
}
public void addBook(Book book) throws LibraryException {
if(indexOf(book) == -1){
if(nrBooks < books.length)
books[nrBooks++] = book;
}
}
private int indexOf(Book book)throws LibraryException {
if(nrBooks < Book[].length){
}
return -1;
}
public static void main(String[]args) throws LibraryException{
Library b = new Library("Sami Frasheri", 700);
b.addBook(new Book("Paul Colhen - Alchemist", 1));
b.addBook(new Book("Paul Colhen - Winners Stand ALone", 2));
b.addBook(new Book("Paul Colhen - The river Piedra I sat and I cried", 3));
System.out.print(b);
}
}
Tried ArrayList In Java?.
They will be able to solve almost all of the problems you are facing. Have a look at contains and add.
Please Note, you must override the hashCode and equals method of your Book object for it to work effectively.
I suggest you use an ArrayList of Book. It will solve all of your problems.
public class Library {
private String name;
private ArrayList<Book> books;
private int maxNumberOfBooks;
public Library(String name, int maxNumberOfBooks) {
this.name = name;
this.maxNumberOfBooks = maxNumberOfBooks;
this.books = new ArrayList<Book>();
}
public void addBook(Book book) {
if (!books.contains(book)) {
books.add(book);
}
}
}
If you need to check both parameters, then do something like:
public void addBook(Book book) {
for (Book b : books) {
if (b.getName().equals(book.getName())) {
return; // another book has the same name
}
if (b.getIsbn() == book.getIsbn()) {
return; // another book has the same ISBN
}
}
books.add(book);
}
The size of an array can't be modified. If you want to add an element, you have to instantiate a new array.
public void addBook(Book book) {
int oldN = books.length;
books = Arrays.copyOf(books, oldN + 1);
books[oldN] = book;
return books;
}
This function could replace indexOf(). It looks for the element in your array.
private boolean contains(Book book) {
for (Book b : books) {
if (b != null && book.equals(b))
return true;
}
return false;
}
I would suggest something like this:
public void addBook(Book book) throws LibraryException {
if(indexOf(book) == -1){//book does not exist
if(nrBooks < (books.length-1)){
books[nrBooks] = book;
++nrBooks;
} else {
throw new LibraryException("Not space for more books.");
}
}
}
private int indexOf(Book book)throws LibraryException {
for(int i=0;i<books.lenght;++i){
if(books[i].getName().equals(book.getName()) && books[i].getIsbn==book.getIsbn){
return i;
}//if
}//for
//else
return -1;
}
Related
I am trying to build an ArrayList that will contain objects. when i add an object to the list i want it to first check the array list for that object. and if it finds it i want it to increase a quantity variable in that object and not create a new object in the list. and then vice versa when removing objects. I have accomplished a way that works when removing an object. But i dont think i fully understand the methods in the arraylist or the logic when creating and arraylist of objects. as when i use .contains or .equals im not getting the desired effect.
public class ItemBag {
private ArrayList<Item> inventory = new ArrayList<Item>();
public ItemBag() {
}
public void addItem(Item objName, int quantity) {
if (inventory.contains(objName)) {
System.out.println("if statement is true!");
int i = inventory.indexOf(objName);
inventory.get(i).setQuantity(inventory.get(i).getQuantity() + quantity);
} else {
inventory.add(objName);
objName.setQuantity(quantity);
}
}
public void removeItems(String itemName, int quantiy) {
for (int i = 0; i < inventory.size(); i++) {
if (inventory.get(i).name() == itemName) {
inventory.get(i).setQuantity(inventory.get(i).getQuantity() - quantiy);
if (inventory.get(i).getQuantity() <= 0) {
inventory.remove(inventory.get(i));
}
}
}
}
public void showInventory() {
for (int i = 0; i < inventory.size(); i++) {
System.out.println(inventory.get(i).name() + " : " + inventory.get(i).getQuantity());
}
}
then when creating the itemBag in another object i am writing
ItemBag merchantItems = new ItemBag();
public void merchantBob() {
merchantItems.addItem(new HealthPotion() ,3);
merchantItems.showInventory();
System.out.println("add 1");
merchantItems.addItem(new HealthPotion(),1);
merchantItems.showInventory();
Items class
package Items;
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
HealthPotion Class
public class HealthPotion extends Potions {
protected int addHealth = 10;
#Override
public int drinkPotion() {
return addHealth;
}
#Override
public String name() {
return "Health Potion";
}
#Override
public int cost() {
return 5;
}
#Override
public String type() {
return "Potion";
}
}
The .contains() method would iterate through the list and use .equals() method to compare each element and check if the provided object exists in the list.
.equals() method would compare the object reference (unless .equals() is overridden) to check if the objects are same.
For reference: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#contains-java.lang.Object-
You can override the .equals() method to compare the values of the provided object in the following way:
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Item providedItem = (Item) object;
return name == providedItem.name
&& cost == providedItem.cost
&& type == providedItem.type;
}
}
This should work
I am trying to write an ADT for a class that incorporates a sequence when there is a small amount of data to store (<1000 key values) and uses a HashTable otherwise. I have to write the sequence class myself but i was delighted to find out that java has it's own built in HashTable class. However, one of the requirements for this ADT is that it must be able to display the previous and next keys (called VINs in the code). I can do this easily with my sequence class, however I was wondering if the built in HashTable class had such a function. Will I have to write my own HashTable class or is there a way I can achieve my goal without having to do so? Thank you all for your help in advance, I really appreciate it!
This is the CVR class (data is passed to this class and it calls upon the sequence or HastTable class)
import java.util.*;
public class CVR
{
//this will be used to generate random alpha numeric numbers
private final static String alphaNumeric="ABDCEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//key
private String VIN;
//threshold (determines which ADT to use)
private int threshold;
//length of key
private int VINLength;
//this is an object of Archive which will hold the data associated with VIN
private Account value;
//TBD
//private Collection<Account> activeVINS;
//HashMap to store all the key-value pairs
//the value come in the form of a stack because,
//multiple events can be associated with the same
//VIN, and must be shown in reverse-chronological order
private Hashtable<String, Stack<Account>> hashRecords;
private sequence seqRecords;
//This will keep track of all VINs and make sure
//none of them are repeated
private HashSet<String> VINRecorder;
private boolean hashTabl=false;
//default constructor
public CVR(int threshold) throws Exception
{
this.setThreshold(threshold);
if (threshold>1000)
{
hashRecords=new Hashtable<>();
hashTabl=true;
}
else
{
seqRecords=new sequence();
hashTabl=false;
}
}
//not sure this is even needed
//parameterized constructor for CVR, takes VIN
//and adds it to VINRecorder
//re-evaluate this method, with this a VIN is added to HashSet, but not to
//HashMap. At the same time I'm not sure We want VINs w/o associated accounts
//to be in HashMap. TBD
//For now actually, I will add them to HashMap, this may change down the line...
/**
public CVR (String VIN) throws Exception
{
this.VIN=VIN;
records=new Hashtable<>();
VINRecorder=new HashSet<>();
add(VIN, null);
//Stack<Account> stack = new Stack<Account>();
//VINRecorder.add(VIN);
}
**/
//accessors and mutators
//VIN getters and setters
public String getVIN()
{
return VIN;
}
public void setVIN(String VIN)
{
this.VIN=VIN;
VINRecorder=new HashSet<>();
VINRecorder.add(VIN);
}
//threshold getters and setters
public int getThreshold()
{
return threshold;
}
//for this one we have to keep in mind the restriction set
//on us in the instructions
public void setThreshold(int threshold) throws Exception
{
if(threshold<100 || threshold>900000)
{
//System.out.println("Invalid input for threshold");
throw new Exception("Invalid input for threshold");
}
else
{
this.threshold=threshold;
}
}
//VINLength getters and setters
public int getVINLength()
{
return VINLength;
}
//again for this one. we need to take the
//instructions into account for this special
//case
public void setVINLength(int VINLength) throws Exception
{
if(VINLength<10 || VINLength>17)
{
throw new Exception("Invalid input for VIN length");
}
else
{
this.VINLength=VINLength;
}
}
//Now onto the methods
//Generate method
//This method should randomly generate a sequence
//containing n new non-existing valid keys
//***Must determine whether the output is a sequence or not
public String generate(int size) throws Exception
{
char[] Arr= alphaNumeric.toCharArray();
String[] ender=new String[size];
//generating random number between 10 and 17
Random r= new Random();
int low=10;
int high=17;
for(int x=0; x<size;x++)
{
int highLow=r.nextInt(high-low)+10;
StringBuilder newString=new StringBuilder();
//making string between length of 10 and 17 randomly
for(int i=0; i<highLow; i++)
{
newString.append(Arr[new Random().nextInt(Arr.length)]);
}
///////////////////
String newVIN=newString.toString();
//System.out.println(newVIN);
//This must be further explored, I do not know why,
//but for some reason it does not work if the first
//condition is not there, to be explored
if(newVIN!=null)
{
}
//stops here for some reason, must find out why, something is wrong with this statement
else if(VINRecorder.contains(newVIN))
{
x--;
}
else
{
ender[x]=newString.toString();
}
ender[x]=newString.toString();
}
//System.out.println("hello");
System.out.println(Arrays.toString(ender));
return Arrays.toString(ender);
}
//method allKeys
//this method should return all keys as a sorted
//sequence in lexicographic order
//the plan here is to use
/**
public LinkedList<Account> allKeys()
{
}
**/
//add method
//****must check to see if must be resized later
public void add(String VIN, Account value) throws Exception
{
if(hashTabl==true)
{
if(!VIN.equals(value.getVIN()))
{
System.out.println("Something went wrong :/");
throw new Exception("VIN does not match account");
}
else if(hashRecords.containsKey(VIN))
{
System.out.println("VIN exists, adding to record");
hashRecords.get(VIN).add(value);
System.out.println("Success!");
}
else
{
System.out.println("New account made, record added!");
Stack<Account> stack = new Stack<Account>();
stack.add(value);
hashRecords.put(VIN, stack);
System.out.println("Success!");
//resize here
//
}
}
else
{
if(value==null)
{
Account saveVIN=new Account(VIN);
seqRecords.add(saveVIN);
}
seqRecords.add(value);
}
}
//remove method
//***must check to see if must be resized later
public void remove(String VIN)
{
if(hashTabl==true)
{
if(hashRecords.containsKey(VIN))
{
hashRecords.remove(VIN);
//resize here
//
}
else
{
System.out.println("Key does not exist in HashTable");
}
}
else
{
seqRecords.removeVIN(VIN);
}
}
//getValues method
public Stack<Account> getValues(String VIN)
{
if(hashTabl == true)
{
if(hashRecords.containsKey(VIN))
{
Stack<Account> values = new Stack<Account>();
values=hashRecords.get(VIN);
return values;
}
else
{
System.out.println("This VIN could not be found in directory");
return null;
}
}
else
{
return seqRecords.getAccount(VIN);
}
}
//nextKey methods
public String nextVIN(String VIN)
{
//unfinished, not sure what to call here
if(hashTabl=true)
{
return hashRecords.
}
else
{
return seqRecords.nextVIN(VIN);
}
}
//previous Accidents method
public Stack<Account> prevAccids(String VIN)
{
if(hashTabl == true)
{
if(hashRecords.contains(VIN))
{
Stack<String> Accids= new Stack<String>();
Stack<Account> temp; //= new Stack<Account>();
temp=hashRecords.get(VIN);
return temp;
/**
String tempString;
while(!temp.isEmpty())
{
tempString=temp.pop().getAccids();
Accids.push(tempString);
}
temp=null;
return Accids;
**/
}
return null;
}
else
{
Stack<Account> temp;
temp=seqRecords.getAccount(VIN);
if(temp==null || temp.isEmpty())
{
System.out.println("This VIN does not exist in the sequence");
return null;
}
else
{
return temp;
}
}
}
//driver method
public static void main(String[] args) throws Exception
{
CVR hello= new CVR(100);
try
{
//System.out.println("hello");
//hello.generate(5);
Account abdcg=new Account("adsj4jandnj4", "Muhammad Ferreira", "perfect record");
Account abdcg1=new Account("adsj4jandnj4","Myriam Ferreira", "Fender Bender");
Account abdcg2= new Account("adsj4jandnj4", null, null);
/////
hello.add("adsj4jandnj4", abdcg);
hello.add("adsj4jandnj4", abdcg2);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my sequence class
import java.util.ArrayList;
import java.util.Stack;
public class sequence
{
private class position
{
private Stack<Account> stack;
private int index;
//constructors
public position()
{
this.stack=new Stack<Account>();
this.index=0;
}
public position(int index, Account acc)
{
this.index=index;
this.stack=new Stack<Account>();
stack.push(acc);
}
//muatators
public int getIndex()
{
return index;
}
public void setIndex(int index)
{
this.index=index;
}
public Stack<Account> getStack()
{
return stack;
}
public void setStack(Stack<Account> newStack)
{
this.stack=newStack;
}
}
private int size;
//private int tail;
private int elementsNum;
//private int currentIndex;
private ArrayList<position> Arr;
public sequence()
{
//currentIndex=0;
size=0;
Arr= new ArrayList<position>(); ;
}
//add first method
public void add(Account account)
{
for(int i=0; i<size; i++)
{
//if already in array, push into its stack
if((Arr.get(i).getStack().peek().getVIN()).equals(account.getVIN()))
{
Arr.get(i).getStack().push(account);
break;
}
//if not in array, make new entry for it
else if(!(Arr.get(i).getStack().peek().getVIN()).equals(account.getVIN()) && i==size-1)
{
position added=new position(size, account);
Arr.add(added);
//currentIndex++;
size++;
}
}
}
//addIndex
//don't think this method is necessary for assignment
/**
public void addIndex(int ind, Account account)
{
position added=new position(ind, account);
Arr.add(ind, added);
size++;
//update indexes of position node
updateIndex();
}
*/
//resizeArray and updates index
public void resize()
{
Arr.trimToSize();
updateIndex();
}
//remove method
public void removeVIN(String VIN)
{
for (int i=0; i<size; i++)
{
if(size==0 || (!VIN.equals(Arr.get(i).getStack().peek().getVIN()) && i==size-1))
{
System.out.println("The Sequence does not contain this VIN");
break;
}
else if(VIN.equals(Arr.get(i).getStack().peek().getVIN()))
{
Arr.remove(i);
resize();
size--;
System.out.println("Successfully removed " +VIN+" and associated values");
}
}
}
//update indexes
public void updateIndex()
{
for (int i=0; i<size; i++)
{
if(Arr.get(i).getIndex() != i)
{
Arr.get(i).setIndex(i);
}
}
}
//Get Values
//Will be used in CVR for both the getValues method (return all values)
//and prevAccids method (return only the accidents not entire account)
public Stack<Account> getAccount(String VIN)
{
for (int i=0; i<size; i++)
{
if(size==0)
{
System.out.println("The Sequence is empty");
break;
}
else if(VIN.equals(Arr.get(i).getStack().peek().getVIN()))
{
return Arr.get(i).getStack();
}
}
return null;
}
//get previous VIN method
public String preVIN(String VIN)
{
for (int i=0; i<size; i++)
{
if((Arr.get(i).getStack().peek().getVIN()).equals(VIN))
{
if(i==0)
{
return "There is no previous VIN, this is the first one";
}
return Arr.get(i-1).getStack().peek().getVIN();
}
}
return null;
}
//get next VIN method
public String nextVIN(String VIN)
{
for (int i=0; i<size; i++)
{
if((Arr.get(i).getStack().peek().getVIN()).equals(VIN))
{
if(i==size-1)
{
return "There is no next VIN, this is the last one";
}
return Arr.get(i+1).getStack().peek().getVIN();
}
}
return null;
}
}
Finally, this is my Account class
//this method is similar to a node, contains
//VIN, Owner, Accidents details
public class Account
{
private String VIN;
private String owner;
private String accidents;
public Account() {};
public Account(String VIN)
{
this.VIN=VIN;
this.owner=null;
this.accidents=null;
}
public Account(String VIN, String owner, String accidents)
{
this.VIN=VIN;
this.owner=owner;
this.accidents=accidents;
}
//mutators
public void setVIN(String VIN)
{
this.VIN=VIN;
}
public String getVIN()
{
return VIN;
}
public void setOwner(String owner)
{
this.owner=owner;
}
public String getOwner()
{
return owner;
}
public void setAccids(String accidents)
{
this.accidents=accidents;
}
public String getAccids()
{
return accidents;
}
}
You may want to use TreeMap instead of obsolete Hashtable - it is sorted by key by design and provides methods to get sequence of keys and related values:
K firstKey()
K lastKey()
K higherKey(K key)
K lowerKey(K key) etc.
As you will probably see from my code I'm quite new with this. I am trying to write a simple program to retrieve the friends of one person. Here is my code:
public class Person {
private String name;
private String friends;
public Person(String aName) {
name = aName;
friends = "";
}
public String getFriends() {
return friends;
}
public void addFriend(Person friend) {
friends = friends + " " + friend.name;
}
public void unfriend(Person nonFriend) {
friends = friends.replace(" " + nonFriend.name, "");
}
public static void main(String[] args) {
Person dana = new Person("Dana");
Person gina = new Person("Gina");
Person john = new Person("John");
dana.addFriend(gina);
dana.addFriend(john);
john.addFriend(gina);
john.addFriend(dana);
john.unfriend(dana);
System.out.println("Dana's friends are: " + dana.getFriends());
System.out.println("Gina's friends are: " + gina.getFriends());
System.out.println("John's friends are: " + john.getFriends());
}
}
Everything works, but I do not know how to create a method that will say:
If Gina is both Dana's and John's friend then clearly Gina's friends will be Dana and John. I know that I can add two lines there gina.addFriend(dana) and gina.addFriend(john), to accomplish the same result, but I would like to know what will the method be for that. Thanks in advance.
First of all, make friends an ArrayList<Friend>.
private ArrayList<Friend> friends;
This has several advantages, including being easier to use and storing the Persons themselves rather than just their names.
Then, change the addFriend method to go in both directions:
public void addFriend(Person friend) {
friends.add(friend);
friend.friends.add(this);
}
In this way, friendships will automatically go back and forth. You should also change unfriend:
public void unFriend(Person friend) {
friends.remove(friend);
friend.friends.remove(this);
}
EDIT: as per a comment above, a set would actually be better, as it can only have one of each value.
I would use a Set, and add a unique Id to person to get around the problem of multiple people having the same name.
Your class will then look like:
public class Person
{
private final String personId;
private final String name;
private final Set<Person> friends;
public Person(String personId, String name) {
super();
this.personId = personId;
this.name = name;
this.friends = new HashSet<Person>();
}
public void addFriend(Person friend) {
if(friend != null && !friends.contains(friend)) {
this.friends.add(friend);
// Optional : if it is a two-way relationship that doesn't need approving etc
friend.addFriend(this);
}
}
public void unfriend(Person nonFriend)
{
if(nonFriend != null && friends.contains(nonFriend)) {
this.friends.remove(nonFriend);
// Optional : if it is a two-way relationship that doesn't need approving etc
nonFriend.unfriend(this);
}
}
public Set<Person> getFriends()
{
return friends;
}
#Override
public String toString() {
return "Person [name=" + name + "]";
}
public static void main(String[] args)
{
Person dana = new Person("D001", "Dana");
Person gina = new Person("G001", "Gina");
Person john = new Person("J001", "John");
dana.addFriend(gina);
dana.addFriend(john);
john.addFriend(gina);
john.addFriend(dana);
john.unfriend(dana);
System.out.println("Dana's friends are: "+dana.getFriends());
System.out.println("Gina's friends are: "+gina.getFriends());
System.out.println("John's friends are: "+john.getFriends());
}
// Equals and Hashcode are very important when using 'contains' and other Set-based methods
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((personId == null) ? 0 : personId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (personId == null) {
if (other.personId != null)
return false;
} else if (!personId.equals(other.personId))
return false;
return true;
}
}
i would suggest to use an arrayList of persons/friends instead of one string.
ArrayList<Person> friends = new ArrayList<Person>;
you add friends by typing:
public void addFriend(Person newFriend){
friends.add(newFriend);
newFriend.friends.add(this);
}
you delete friends by typing:
public void unfriend(Person noFriend){
for(int i = 0; i < this.friends.size(); i++){
if(this.friends.get(i).name.equals(noFriend.name){
this.friends.delete(i);
}
}
for(int i = 0; i < noFriend.friends.size(); i++){
if(noFriend.friends.get(i).name.equals(this.name){
noFriend.friends.delete(i);
}
}
}
to show the whole list of friends:
public void showFriends(){
for(int i = 0; i < this.friends.size(); i++){
System.out.println(this.friends.get(i));
}
}
I am trying to use compareTo method to compare two different names. After running the first attempt the program terminates immediately without returning anything. How can I modify this compareTo method to compare the names (Name n and Name n2) and return the result (-1, 1 or 0)? And obviously a print statement can be added to display (equal, before , or after) for the comparison. Thanks for any assistance.
//First attempt
public class Name implements Comparable<Name> {
private String Name;
public Name(String string) {
// TODO Auto-generated constructor stub
}
public String getName() {
return Name;
}
public int compareTo(Name other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
Name n = new Name("jennifer");
n.getName();
Name n2 = new Name("paul");
n2.getName();
}
}
//second attempt
public class Name implements Comparable<String> {
private String Name;
public String getName() {
return Name;
}
public int compareTo(String other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
String Name = new String("jennifer");
String other = new String("paul");
}
}
//First attempt
public class Name {
public static void main(String[] args) {
String n = new String("jennifer");
String n2 = new String("paul");
if (n.compareTo(n2) < 0) {
System.out.println(n +" is before than " +n2);
} else if (n.compareTo(n2) > 0) {
System.out.println(n +" is after than " +n2);
} else if (n.compareTo(n2) == 0) {
System.out.println(n +" is equals to " +n);
}
}
}
Outoput:
jennifer is before than paul
By the way, check this out because every programming language has its own set of rules and conventions and for variables in Java is like this:
If the name you choose consists of only one word, spell that word in
all lowercase letters. If it consists of more than one word,
capitalize the first letter of each subsequent word.
public class Name implements Comparable<Name> {
private String name;
public Name(String name) {
this.name=name;
}
public String getName() {
return name;
}
public int compareTo(Name other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
Name n = new Name("jennifer");
n.getName();
Name n2 = new Name("paul");
n2.getName();
System.out.println(n.getName());
System.out.println(n2.getName());
System.out.println(n2.compareTo(n));
}
}
OUTPUT :
jennifer
paul
1
I know this must be a fundamental design problem because I clearly can't do this. I want to call the ownGrokk, ownTyce, etc methods from another class depending on the value of the integer assigned to OwnedSpirits(int). This in turn fills arrays.
The problem is, I do this multiple times, and doing it from another class it seems like I have to make a new object every time to pass the new int argument, and doing so resets the value of spiritInstance. And, since that resets to zero, the arrays don't fill properly. I try to print out my array values later and I get an "ArrayIndexOutOfBoundsException".
public class OwnedSpirits {
private int spiritTypeInt = 0;
public static int spiritInstance=0;
public static int[] spiritarray = new int[9];
public static String[] spiritName = new String[9];
public static int[] party = new int[3];
public OwnedSpirits(int spiritcall){
if(spiritcall == 1){
ownGrokk();
}
if(spiritcall == 2){
ownRisp();
}
if(spiritcall == 3){
ownTyce();
}
if(spiritcall == 4){
ownDaem();
}
if(spiritcall == 5){
ownCeleste();
}
}
private void ownGrokk(){
spiritName[spiritInstance] = "Grokk";
spiritInstance++;
}
private void ownRisp(){
spiritName[spiritInstance] = "Risp";
spiritInstance++;
}
private void ownDaem(){
spiritName[spiritInstance] = "Daem";
spiritInstance++;
}
private void ownCeleste(){
spiritName[spiritInstance] = "Celeste";
spiritInstance++;
}
private void ownTyce(){
spiritName[spiritInstance] = "Tyce";
spiritInstance++;
}
and this code is in another class, where it attempts to call the methods to fill the array
buttonConfirm.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
if(xcounter==3){
for(x=0; x<3; x++){
if(setdaemtrue == true){
new OwnedSpirits(4);
}
if(setrisptrue == true){
new OwnedSpirits(2);
}
if(setcelestetrue == true){
new OwnedSpirits(5);
}
if(settycetrue == true){
new OwnedSpirits(3);
}
if(setgrokktrue == true){
new OwnedSpirits(1);
}
}
}
}
});
and finally in yet another class:
System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);
#Override
public void show() {
System.out.println(partylist[0]);
System.out.println(partylist[1]);
System.out.println(partylist[2]);
spiritlist.setItems(partylist);
table.add(spiritlist);
table.setFillParent(true);
stage.addActor(table);
}
If the last part is confusing, it's because I am using libgdx. the print statements are there just to try to figure out why my list was having an error
I can show you what I would do to handle Spirits, and Parties.
The Spirit class, contains name and current party its assigned to:
package com.stackoverflow.spirit;
public class Spirit {
private String name;
private Party party;
private SpiritType type;
private static int id = 0;
public static enum SpiritType {
Grokk, Risp, Tyce, Daem, Celeste
};
public Spirit(String name, SpiritType type) {
create(name, type);
}
public Spirit(SpiritType type) {
create(null, type);
}
// This is to handle Java inexistance of default parameter values.
private void create(String name, SpiritType type)
{
Spirit.id++;
this.name = (name == null) ? (type.name() + " " + id) : name;
this.type = type;
}
public String getName() {
return name;
}
public Party getParty() {
return party;
}
public SpiritType getType() {
return type;
}
/**
* Used internally by #see Party
* #param party the party this Spirit belongs
*/
public void setParty(Party party) {
this.party = party;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString()
{
return this.name;
}
}
Finally the Party class, contains a set of Spirits, you can add and remove Spirits from the party.
package com.stackoverflow.spirit;
import java.util.HashSet;
public class Party {
private HashSet<Spirit> spirits = new HashSet<Spirit>();
private static int id = 0;
private String name = "Party " + Party.id++;;
public Party() {
}
public Party(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(Spirit spirit) {
if (!spirits.contains(spirit)) {
spirits.add(spirit);
if (spirit.getParty() != null) {
//Remove from previous party to update the other party set
spirit.getParty().remove(spirit);
}
spirit.setParty(this);
} else {
// throw new SpiritAlreadyOnParty();
}
}
public void remove(Spirit spirit)
{
if (spirits.contains(spirit))
{
spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
spirits.remove(spirit);
}
else {
//throw new SpiritNotInParty();
}
}
public boolean isOnParty(Spirit spirit) {
return spirits.contains(spirit);
}
public ArrayList<Spirit> getSpirits()
{
return new ArrayList<Spirit>(spirits);
}
public int getPartySize() {
return spirits.size();
}
public String getPartyInfo()
{
StringBuilder builder = new StringBuilder();
builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
for (Spirit s : spirits)
{
builder.append(s.getName() + "\n");
}
return builder.toString();
}
#Override
public String toString()
{
return this.name;
}
}
Here I use the Spirit and Party classes, you could add more functionality, like properties for party strength, magic buffs on the party, etc:
package com.stackoverflow.spirit;
import com.stackoverflow.spirit.Spirit.SpiritType;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Party griffindor = new Party("Griffindor"), slytherin = new Party(
"Slytherin");
// You can also do for (SpiritType type : SpiritType.values() then
// type.ordinal()
for (int i = 0; i < SpiritType.values().length; i++) {
griffindor.add(new Spirit(SpiritType.values()[i]));
slytherin.add(new Spirit(SpiritType.values()[i]));
}
Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);
slytherin.add(mySpirit);
System.out.println("Name of party:" + mySpirit.getParty().getName());
System.out.println("Is on griffindor?:"
+ griffindor.isOnParty(mySpirit));
// What now?
griffindor.add(mySpirit);
System.out.println("Is " + mySpirit.getName() + " on "
+ slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));
System.out.println(mySpirit.getName() + " is now on "
+ mySpirit.getParty() + "\n");
System.out.println(griffindor.getPartyInfo());
System.out.println(slytherin.getPartyInfo());
}
}
P.D: I'm not a HP fan.