My getName() function is coded right but throws an NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
So I was trying to code a viewer class and then create a list which is based on these viewers as another Class called ViewerList.
Usually everything should work but somehow it doesn't let me use the methods "toLine()" and "getName()". If anyone here could help me it would be awesome.
As in title the only error-report i get is NullPointerException.
This is the Viewer class:
public class Viewer {
private int points = 0;
private String name;
public Viewer(String name, int points) {
this.points = points;
this.name = name;
}
public int getPoints() {
return points;
}
public String toLine() {
String line = getName() + " " + getPoints();
return line;
}
public void addPoint(int amount){
points += amount;
}
public String getName(){
return name;
}
This is the ViewerList class:
public class ViewerList {
private Viewer[] array;
private int nextFreeSlot = 0;
private int count = 0;
public ViewerList(int capacity){
array = new Viewer[capacity];
}
public void add(Viewer o){
if (nextFreeSlot == array.length) {
throw new IllegalStateException("Liste ist voll!");
}
array[nextFreeSlot] = o;
count++;
nextFreeSlot++;
}
public Viewer[] getArray(){
return array;
}
public Viewer get(int index) {
return array[index];
}
public int getCapacity() {
return array.length;
}
public int getElementCount() {
return count;
}
public void addPoints () {
if(array.length > 0){
for(Viewer v : array){
v.addPoint(1);
}
}
}
public int getPointsOf(String viewerName) {
int points = 0;
String vName = "";
for(Viewer v : array){
vName = v.getName(); // The v.getName() method is an error here
if(viewerName.equals(vName)) {
points = v.getPoints();
}
}
return points;
}
public boolean contains(String name) {
boolean contains = false;
for(Viewer v : array){
if(name.equals(v.getName())){ // also here i get the NullPointerException
contains = true;
break;
}
}
return contains;
}
}
Also if you need the stack trace then here it is:
java.lang.NullPointerException
at bot.PointList.getPointsOf(PointList.java:50)

Null pointer exception occurs when you do not initialize the declared variable. My guess in your case is the string name. Debug your code by adding a print statement in your getName() method.

Related

Method returning from one class to another class

I'm currently learning OOP in Java, I have tried to write a mini database system, everything works well but I have two methods which are located in class CivilStatus that are not working well and they keep giving me 0 as a return, the methods are PersonAge(String NationalId) and CountSingle(). I would be grateful if anyone would have solved this bug for me.
public class Person101 {
String nationalIdString;
String nameString;
int Age;
Boolean marriedBoolean;
Person101(String newId, String name, Boolean newMarried) {
nationalIdString = newId;
nameString = name;
marriedBoolean = newMarried;
Age = 0;
}
public String getId() {
return nationalIdString;
}
public String getName() {
return nameString;
}
public int getAge() {
return Age;
}
public Boolean getMarriedStatus() {
return marriedBoolean;
}
public void setAge(int newAge) {
Age = newAge;
}
public void setName(String newName) {
nameString = newName;
}
public void print() {
System.out.println("The name is: " + nameString + " ,Id is: " + nationalIdString);
}
public boolean SingleJordanian() {
if ((nationalIdString.contains("Jor")) && (marriedBoolean == false)) {
return true;
} else {
return false;
}
}
public void birthday() {
Age++;
}
}
import java.util.ArrayList;
public class CivilStatus1 {
String nameString;
ArrayList<Person101> personsArrayList;
CivilStatus1(String newName) {
nameString = newName;
personsArrayList = new ArrayList<Person101>();
}
public String getName() {
return nameString;
}
public ArrayList<Person101> getPerson101s() {
return personsArrayList;
}
public int PersonAge(String NationalId) {
int newAge = 0;
for (Person101 person101 : personsArrayList) {
if (person101.nationalIdString.equals(NationalId)) {
newAge = person101.Age;
} else {
}
}
return newAge;
}
public int CountSingle() {
int counter = 0;
for (Person101 person101 : personsArrayList) {
if (person101.SingleJordanian()) {
counter = counter + 1;
} else {
}
}
return counter;
}
}
Thanks in advance!
The problem is the same for both methods. Writing
personsArrayList = new ArrayList<Person101>();
creates an ArrayList, but it's empty, as you have not added any items to it. Then, when you try looping over the ArrayList
for (Person101 person101 : personsArrayList) {
if (person101.nationalIdString.equals(NationalId)) {
newAge = person101.Age;
} else {
}
}
It doesn't even enter the loop, as there is nothing to loop over.
You should first add some items to the loop, for instance:
Person101 person1 = new Person101();
personsArrayList.add(person1);
As an aside, I would suggest that you shouldn't include the variable types in the name, e.g. personsArrayList, marriedBoolean. You already specified the type when you declared it
ArrayList<Person101> personsArrayList;
Rather just name them persons, married etc.
Just my 2 cents :).
There are a few things that could be causing issues.
Firstly with the variables of each class it is better practice to specify if they are public
public String nationalIdString;
public String nameString;
public int Age;
public Boolean marriedBoolean;
or private.
private String nationalIdString;
private String nameString;
private int Age;
private Boolean marriedBoolean;
Otherwise the variables are package protected which may causing issues with accessing the variables.
If you set them to private you can access them using getter methods
public String getNationalIdString(){
return nationalIdString;
}
If you are using getters your method should look something like this
public int PersonAge(String NationalId) {
int newAge = 0;
for (Person101 person101 : personsArrayList) {
if (person101.getNationalIdString().equals(NationalId)) {
newAge = person101.getAge();
} else {
}
}
return newAge;
}
I'm not sure if this is causing the problem but it may be.
The other suggestion is using boolean instead of Boolean unless there is a specific reason why you are using it.
To help debug your code I suggest doing something like this
public int PersonAge(String NationalId) {
int newAge = 0;
for (Person101 person101 : personsArrayList) {
System.out.println("Looking for: " + NationalID + " current person: " + person101.NationalID);
if (person101.nationalIdString.equals(NationalId)) {
newAge = person101.Age;
}
}
return newAge;
}
This should help you locate the problem, you can also add the person's name so you can compare that to the data you inputted. I also removed the else branch of the if statement as it was not used.
Also check that SingleJordanian() is working as expected as that may be root of CountSingle() not working as intended.

Can the built in HashTable class show previous and next keys?

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.

How to sort an array that is combined by "null" and Strings?

I have got an array of 20:
private Karte[] deckArr;
deckArr = new Karte[20];
Now I want to sort the array by card-names every time a new card is added.
P.S. the cards are added 1 by 1 after clicking on a button, so there are empty spaces in the array.
Since the...
Arrays.sort(deckArr.getName());
...method does not work here I asked myself how it is done.
Karte(card) class:
package Model;
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements ComparableContent<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
#Override
public boolean isLess(Karte karte) {
if (getName().compareTo(karte.getName()) < 0){
return true;
}else{
return false;
}
}
#Override
public boolean isEqual(Karte karte) {
return getName() == karte.getName();
}
#Override
public boolean isGreater(Karte karte) {
if (getName().compareTo(karte.getName()) > 0){
return true;
}else{
return false;
}
}
}
Any help is appreciated!
Why not just use ArrayList instead? Easier to add, remove elements and you will never have empty slots.
Anyway to sort you can use Collections.sort like this:
deckArr = new ArrayList<Karte>();
Collections.sort(deckArr, Comparator.comparing(karte -> karte.getName()));
Java 8 offers a simple solution:
The Comparable Interface has a static method that creates a Comaprator with an extractor.
Comparator<Card> comp = Comparator.comparing(Karte::getName);
With this using a sorting method (e.g. Arrays.sort) is easy to call.
On top of that, to solve your nullpointer problem, the Comparator Interface offers another two functions: NullsLast and nullsFirst.
Comparator<Card> comp = Comparator.nullsLast(Comparator.comparing(Card::getName));
For me this looks like the easiest solution to your question :)
This should solve your problem. Implements the Comparable interface.
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements Comparable<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
public int compareTo(Karte karte) {
return this.name.compareTo(karte.getName());
}
}
Then you just need to call Arrays.sort(deckArr);
You need to check for nulls and just call below--
Arrays.sort(deckArr, new Comparator<Karte>() {
#Override
public int compare(Karte karte1, Karte karte2) {
if (karte1.getName() == null && karte2.getName() == null) {
return 0;
}
if (karte1.getName() == null) {
return 1;
}
if (karte2.getName() == null) {
return -1;
}
return karte1.getName().compareTo(karte2.getName());
}});

What is the correct way to do this?

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.

java: ArrayList how order [duplicate]

This question already has answers here:
How to sort List of objects by some property
(17 answers)
Closed 8 years ago.
I have this class:
public class Media {
double supporto;
double i_m;
String idSentence;
public Media(double supporto,double i_m,String idSent){
this.supporto=supporto;
this.i_m=i_m;
this.idSentence=idSent;
}
public double getSupporto(){
return this.supporto;
}
public double getI_m(){
return this.i_m;
}
public String getIdSentence(){
return this.idSentence;
}
public String toString(){
return this.supporto+" - "+this.i_m+" - "+this.idSentence;
}
}
and add in an ArrayList text these values​​:
ArrayList<Media> m=new ArrayList<Media>();
m.add(new Media(0.2545,0.2365,"id002"));
m.add(new Media(0.8745,0.4658,"id005"));
m.add(new Media(0.1599,0.6580,"id0010"));
How do I sort this array in descending order of the value of the first class Media?
I want to get this order:
0.1599,0.6580,"id0010"
0.2545,0.2365,"id002"
0.8745,0.4658,"id005"
EDIT
I solved this way:
public class Media implements Comparable<Object>{
double supporto;
double i_m;
String idSentence;
public Media(double supporto,double i_m,String idSent){
this.supporto=supporto;
this.i_m=i_m;
this.idSentence=idSent;
}
public double getSupporto(){
return this.supporto;
}
public double getI_m(){
return this.i_m;
}
public String getIdSentence(){
return this.idSentence;
}
public String toString(){
return this.supporto+" - "+this.i_m+" - "+this.idSentence;
}
#Override
public int compareTo(Object arg0) {
if(this.supporto==((Media) arg0).getSupporto()) return 0;
else if((this.supporto)>((Media)arg0).getSupporto()) return 1;
else return -1;
}
}
In the main method I order the m ArrayList:
Collections.sort(m);
You need to make Fruit Comparable
public class Media implements Comparable<Fruit> {
public int compareTo(Fruit compareFruit) {
int compareQuantity = ((Media) compareFruit).getSupporto();
//ascending order
return this.supporto - compareQuantity;
//descending order
//return compareQuantity - this.supporto;
}
...
}
Arrays.sort(m);
Some more info :
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
You can sort it with your own comparator
m.sort(new Comparator<Media>() {
#Override
public int compare(Media o1, Media o2) {
return Double.compare(o1.getSupporto(), o2.getSupporto());
}
});
this will sort it the way you like. If you need this in many pleaces, i would suggest however creating static comparator like:
private static Comparator<Media> supportoComparator = new Comparator<Media>() {
#Override
public int compare(Media o1, Media o2) {
if (o1 != null && o2 != null) {
return Double.compare(o1.getSupporto(), o2.getSupporto());
} else {
throw new IllegalArgumentException();
}
}
};
Above code is in class Media, and then you use it like:
m.sort(Media.GET_SUPPORTO_COMPARATOR());
and its done

Categories

Resources