Passing Objects through Heap Sort - object

Having issues trying to pass an object class to be sorted via Heap Sort. Basically I have a class which holds employee data such as names, address, phone numbers and employee ID. We are to use Heap Sort to pass this class as a object and sort it by employee ID. My main issue is converting my heap sort structures to where they can take objects. This is for a beginning data structures course so we're not allowed to use advanced techniques. My road block is I'm stumped as to how to pass my objects into the heap sort methods which currently only take primitive data types.
Office Class:
public class Office_Staff
{
public String Name , Dept , Phonenumber;
public int Id, years;
Office_Staff()
{
Id = ("");
Name = ("");
Dept = ("");
Phonenumber = ("");
years = 0;
}
Office_Staff(int empid ,String empname, String empdept , String empphone, int service)
{
Id = empid;
Name = empname;
Dept = empdept;
Phonenumber = empphone;
years = service;
}
public void setId(int empid)
{
Id = empid;
}
public void setName(String empname)
{
Name = empname;
}
public void setDept(String empdept)
{
Dept = empdept;
}
public void setPhone(String empphone)
{
Phonenumber = empphone;
}
public void setYears(int service)
{
years = service;
}
public String getId()
{
return Id;
}
public String getName()
{
return Name;
}
public String getDept()
{
return Dept;
}
public String getPhone()
{
return Phonenumber;
}
public int getYears()
{
return years;
}
public String toString()
{
String str = "Office_Staff Name : " + Name + "Office_Staff ID : " + Id +
"Office_Staff Deaprtment : " + Dept + "Office_Staff Phone Number : "
+ Phonenumber + "Years Active : " + years;
return str;
}
}
Heap Sort:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
class zNode
{
private int iData;
public zNode(int key)
{
iData = key;
}
public int getKey()
{
return iData;
}
public void setKey(int k)
{
iData = k;
}
}
class HeapSort
{
private int [] currArray;
private int maxSize;
private int currentSize;
private int currIndex;
HeapSort(int mx)
{
maxSize = mx;
currentSize = 0;
currArray = new int[maxSize];
}
//buildheap
public boolean buildHeap(int [] currArray)
{
int key = currIndex;
if(currentSize==maxSize)
return false;
int newNode = key;
currArray[currentSize] = newNode;
siftUp(currArray , currentSize++);
return true;
}
//siftup
public void siftUp(int [] currArray , int currIndex)
{
int parent = (currIndex-1) / 2;
int bottom = currArray[currIndex];
while( currIndex > 0 && currArray[parent] < bottom )
{
currArray[currIndex] = currArray[parent];
currIndex = parent;
parent = (parent-1) / 2;
}
currArray[currIndex] = bottom;
}
//siftdown
public void siftDown(int [] currArray , int currIndex)
{
int largerChild;
int top = currArray[currIndex];
while(currIndex < currentSize/2)
{
int leftChild = 2*currIndex+1;
int rightChild = leftChild+1;
if(rightChild < currentSize && currArray[leftChild] < currArray[rightChild] )
largerChild = rightChild;
else
largerChild = leftChild;
if( top >= currArray[largerChild] )
break;
currArray[currIndex] = currArray[largerChild];
currIndex = largerChild;
}
currArray[currIndex] = top;
}
//remove max element
public int removeMaxElement(int [] currArray)
{
int root = currArray[0];
currArray[0] = currArray[--currentSize];
siftDown(currArray , 0);
return root;
}
//heapsort
private void _sortHeapArray(int [] currArray)
{
while(currentSize != 0)
{
removeMaxElement(currArray);
}
}
public void sortHeapArray()
{
_sortHeapArray(currArray);
}
//hepify
private int[] heapify(int[] currArray)
{
int start = (currentSize) / 2;
while (start >= 0)
{
siftDown(currArray, start);
start--;
}
return currArray;
}
//swap
private int[] swap(int[] currArray, int index1, int index2)
{
int swap = currArray[index1];
currArray[index1] = currArray[index2];
currArray[index2] = swap;
return currArray;
}
//heapsort
public int[] _heapSort(int[] currArray)
{
heapify(currArray);
int end = currentSize-1;
while (end > 0)
{
currArray = swap(currArray,0, end);
end--;
siftDown(currArray, end);
}
return currArray;
}
public void heapSort()
{
_heapSort(currArray);
}

Related

Hazelcast Predicate SQL into map

I'm trying to build a method that deletes entries with attributes that are not null, but I keep failing in predicates and I don't know how to implement properly the predicate because hazelcast doesn't take "NOT NULL" or "IS NULL" as a where clause Any idea how can I find into the map the values I need to search to delete them?
the method
public int removeEntry(String CacheName, String claveReq, int id_interno_pe, String cod_nrbe_en, int num_sec_ac) {
int counter = 0;
IMap<String, ResponseSerializablePlus> map = clientInstance.getMap(CacheName);
// Predicate claveReqQuery = Predicates.equal("claveReq", claveReq);
// Predicate idInternoQuery = Predicates.equal("id_interno_pe", id_interno_pe);
// Predicate codNrbeQuery = Predicates.equal("cod_nrbe_en", cod_nrbe_en);
// Predicate numSecQuery = Predicates.equal("num_sec_ac", num_sec_ac);
// Predicate query = Predicates.and(idInternoQuery,codNrbeQuery,numSecQuery);
Predicate query = Predicates.sql("id_interno_pe IS NOT NULL");
if (!map.isEmpty()) {
for (ResponseSerializablePlus entry : map.values(query)) {
System.out.println("Entry "+entry.toString()+" Found");
map.delete(entry);
counter++;
}
System.out.println("Map Size ->"+map.size());
System.out.println("Deleted entries -> "+counter);
return counter;
}else {
System.out.println("No matches");
return 0;
}
}
the main class ResponseSerializablePlus
public class ResponseSerializablePlus implements IdentifiedDataSerializable{
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializablePlus(int id_interno_pe, String cod_nrbe_en, int num_sec_ac, int statusCode,
HashMap<String, List<String>> headers, byte[] content) {
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializablePlus() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
out.writeInt(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializablePlusFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializablePlusFactory.RESPONSE_SERIALIZABLE_PLUS_CLASS;
}
#Override
public String toString() {
return "ResponseSerializablePlus [id_interno_pe=" + id_interno_pe + ", cod_nrbe_en=" + cod_nrbe_en
+ ", num_sec_ac=" + num_sec_ac + ", statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
}
It's indeed not supported, and it's document, along with the alternative option. Have a look here: https://github.com/hazelcast/hazelcast/blob/3cb8ce1fc3bb848aced6c87a30bf7b31aec16cf7/hazelcast/src/main/java/com/hazelcast/query/Predicates.java#L492-L497

XPages: How to acces an application scope bean from a session scope bean

I need a value from my application scope managed bean in my session scope managed bean. Not sure how to get this done. Saw a poste here: https://guedebyte.wordpress.com/2012/05/19/accessing-beans-from-java-code-in-xpages-learned-by-reading-the-sourcecode-of-the-extensionlibrary/ But I get a bunch of errors... I also found this: JSF 2.0 Accessing Application Scope bean from another Bean so IM thinking maybe I need to redefine my application bean??? Totally clueless...
How can I make that happen?
Here is the application scope bean's code:
public class AppConfig implements Serializable {
private static final long serialVersionUID = 2768250939591274442L;
public AppConfig() {
initDefaults();
initFromConfigDoc();
}
// Control the number of entries displayed in the widgets
private int nbWidgetFavorites = 0;
private int nbWidgetMostPopular = 0;
private int nbWidgetToolbox = 0;
// Control the number of entries to display in the What's new view
private int nbWhatsNew = 0;
private String showDetailsWhatsNew = "no";
//controls various search options
private int nbSearchResults = 0;
private int nbMaxSearchResults = 0;
//the home page to use for each language
private String homePageUNID_FR = "";
private String homePageUNID_EN = "";
//application email address to use (webmaster)
// DEV ADDRESS
private String appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
// UAT ADDRESS
// PROD ADDRESS
//path to the stats DB
private String statsDB = "";
//application message, if needed
private String systemMessageFR = "";
private String systemMessageEN = "";
//default lang (defined here as session bean will read from the App bean first to
// see if there's a value stored there)
private String defaultLang = "";
//default prov
private String defaultProv = "";
// show Province drop down?
private String showProv = "no";
//various text for "share this link" emails
private String senderEmail = "";
private String senderName = "";
private String appURL = "";
private String emailText = "";
private String clickLinkText = "";
private String emailFooter = "";
private String messageIntro = "";
private String allowRatingModification = "";
/*****************************************************************************/
private void initDefaults() {
// Control the number of entries displayed in the widgets
nbWidgetFavorites = 10;
nbWidgetMostPopular = 10;
nbWidgetToolbox = 10;
nbWhatsNew = 15;
showDetailsWhatsNew = "no";
nbSearchResults = 25;
nbMaxSearchResults = 100;
homePageUNID_FR = "";
homePageUNID_EN = "";
appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
statsDB = "belair\\xBiblioStats.nsf";
systemMessageFR = "";
systemMessageEN = "";
defaultLang = "FR";
defaultProv = "QC";
showProv = "no";
allowRatingModification = "1";
}
/*****************************************************************************/
public boolean persistToConfigDoc() {
//write content of sessionScope vars to config doc
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc == null) {
doc = db.createDocument();
doc.replaceItemValue("form", "AppConfig");
}
doc.replaceItemValue("nbWidgetFavorites", this.nbWidgetFavorites);
doc.replaceItemValue("nbWidgetMostPopular", this.nbWidgetMostPopular);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWhatsNew", this.nbWhatsNew);
doc.replaceItemValue("showDetailsWhatsNew", this.showDetailsWhatsNew);
doc.replaceItemValue("nbSearchResults", this.nbSearchResults);
doc.replaceItemValue("nbMaxSearchResults", this.nbMaxSearchResults);
doc.replaceItemValue("homePageUNID_FR", this.homePageUNID_FR);
doc.replaceItemValue("homePageUNID_EN", this.homePageUNID_EN);
doc.replaceItemValue("appEmailAddress", this.appEmailAddress);
doc.replaceItemValue("statsDB", this.statsDB);
doc.replaceItemValue("systemMessageFR", this.systemMessageFR);
doc.replaceItemValue("systemMessageEN", this.systemMessageEN);
doc.replaceItemValue("defaultLang", this.defaultLang);
doc.replaceItemValue("defaultProv", this.defaultProv);
doc.replaceItemValue("showProv", this.showProv);
doc.replaceItemValue("senderEmail", this.senderEmail);
doc.replaceItemValue("senderName", this.senderName);
doc.replaceItemValue("appURL", this.appURL);
doc.replaceItemValue("emailText", this.emailText);
doc.replaceItemValue("clickLinkText", this.clickLinkText);
doc.replaceItemValue("emailFooter", this.emailFooter);
doc.replaceItemValue("messageIntro", this.messageIntro);
doc.replaceItemValue("allowRatingModification", this.allowRatingModification);
doc.save();
return true;
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/*****************************************************************************/
public void initFromConfigDoc() {
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc != null) {
//load default values
if(doc.hasItem("nbWidgetFavorites")) {
int tmp = doc.getItemValueInteger("nbWidgetFavorites");
if(tmp > 0) {
this.nbWidgetFavorites = tmp;
}
}
if(doc.hasItem("nbWidgetMostPopular")) {
int tmp = doc.getItemValueInteger("nbWidgetMostPopular");
if(tmp > 0) {
this.nbWidgetMostPopular = tmp;
}
}
if(doc.hasItem("nbWidgetToolbox")) {
int tmp = doc.getItemValueInteger("nbWidgetToolbox");
if(tmp > 0) {
this.nbWidgetToolbox = tmp;
}
}
if(doc.hasItem("nbWhatsNew")) {
int tmp = doc.getItemValueInteger("nbWhatsNew");
if(tmp > 0) {
this.nbWhatsNew = tmp;
}
}
if(doc.hasItem("showDetailsWhatsNew")) {
String tmp = doc.getItemValueString("showDetailsWhatsNew");
this.showDetailsWhatsNew = tmp;
}
if(doc.hasItem("nbSearchResults")) {
int tmp = doc.getItemValueInteger("nbSearchResults");
if(tmp > 0) {
this.nbSearchResults = tmp;
}
}
if(doc.hasItem("nbMaxSearchResults")) {
int tmp = doc.getItemValueInteger("nbMaxSearchResults");
if(tmp > 0) {
this.nbMaxSearchResults = tmp;
}
}
if(doc.hasItem("homePageUNID_FR")) {
String tmp = doc.getItemValueString("homePageUNID_FR");
if(!"".equals(tmp)) {
this.homePageUNID_FR = tmp;
}
}
if(doc.hasItem("homePageUNID_EN")) {
String tmp = doc.getItemValueString("homePageUNID_EN");
if(!"".equals(tmp)) {
this.homePageUNID_EN = tmp;
}
}
if(doc.hasItem("appEmailAddress")) {
String tmp = doc.getItemValueString("appEmailAddress");
if(!"".equals(tmp)) {
this.appEmailAddress = tmp;
}
}
if(doc.hasItem("statsDB")) {
String tmp = doc.getItemValueString("statsDB");
if(!"".equals(tmp)) {
this.statsDB = tmp;
}
}
if(doc.hasItem("systemMessageFR")) {
String tmp = doc.getItemValueString("systemMessageFR");
if(!"".equals(tmp)) {
this.systemMessageFR = tmp;
}
}
if(doc.hasItem("systemMessageEN")) {
String tmp = doc.getItemValueString("systemMessageEN");
if(!"".equals(tmp)) {
this.systemMessageEN = tmp;
}
}
if(doc.hasItem("defaultLang")) {
String tmp = doc.getItemValueString("defaultLang");
if(!"".equals(tmp)) {
this.defaultLang = tmp;
}
}
if(doc.hasItem("defaultProv")) {
String tmp = doc.getItemValueString("defaultProv");
if(!"".equals(tmp)) {
this.defaultProv = tmp;
}
}
if(doc.hasItem("showProv")) {
String tmp = doc.getItemValueString("showProv");
if(!"".equals(tmp)) {
this.showProv = tmp;
}
}
if(doc.hasItem("senderEmail")) {
String tmp = doc.getItemValueString("senderEmail");
if(!"".equals(tmp)) {
this.senderEmail = tmp;
}
}
if(doc.hasItem("senderName")) {
String tmp = doc.getItemValueString("senderName");
if(!"".equals(tmp)) {
this.senderName = tmp;
}
}
if(doc.hasItem("appURL")) {
String tmp = doc.getItemValueString("appURL");
if(!"".equals(tmp)) {
this.appURL = tmp;
}
}
if(doc.hasItem("emailText")) {
String tmp = doc.getItemValueString("emailText");
if(!"".equals(tmp)) {
this.emailText = tmp;
}
}
if(doc.hasItem("clickLinkText")) {
String tmp = doc.getItemValueString("clickLinkText");
if(!"".equals(tmp)) {
this.clickLinkText = tmp;
}
}
if(doc.hasItem("emailFooter")) {
String tmp = doc.getItemValueString("emailFooter");
if(!"".equals(tmp)) {
this.emailFooter = tmp;
}
}
if(doc.hasItem("messageIntro")) {
String tmp = doc.getItemValueString("messageIntro");
if(!"".equals(tmp)) {
this.messageIntro = tmp;
}
}
//allowRatingModification
if(doc.hasItem("allowRatingModification")) {
String tmp = doc.getItemValueString("allowRatingModification");
if(!"".equals(tmp)) {
this.allowRatingModification = tmp;
}
}
}
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*****************************************************************************/
public int getNbWidgetFavorites() {
return nbWidgetFavorites;
}
public void setNbWidgetFavorites(int nbWidgetFavorites) {
this.nbWidgetFavorites = nbWidgetFavorites;
}
public int getNbWidgetMostPopular() {
return nbWidgetMostPopular;
}
public void setNbWidgetMostPopular(int nbWidgetMostPopular) {
this.nbWidgetMostPopular = nbWidgetMostPopular;
}
public int getNbWidgetToolbox() {
return nbWidgetToolbox;
}
public void setNbWidgetToolbox(int nbWidgetToolbox) {
this.nbWidgetToolbox = nbWidgetToolbox;
}
public void setNbWhatsNew(int nbWhatsNew) {
this.nbWhatsNew = nbWhatsNew;
}
public int getNbWhatsNew() {
return nbWhatsNew;
}
public void setShowDetailsWhatsNew(String showDetailsWhatsNew) {
this.showDetailsWhatsNew = showDetailsWhatsNew;
}
public String getShowDetailsWhatsNew() {
return showDetailsWhatsNew;
}
public int getNbSearchResults() {
return nbSearchResults;
}
public void setNbSearchResults(int nbSearchResults) {
this.nbSearchResults = nbSearchResults;
}
public int getNbMaxSearchResults() {
return nbMaxSearchResults;
}
public void setNbMaxSearchResults(int nbMaxSearchResults) {
this.nbMaxSearchResults = nbMaxSearchResults;
}
public String getHomePageUNID_FR() {
return homePageUNID_FR;
}
public void setHomePageUNID_FR(String homePageUNID_FR) {
this.homePageUNID_FR = homePageUNID_FR;
}
public String getHomePageUNID_EN() {
return homePageUNID_EN;
}
public void setHomePageUNID_EN(String homePageUNID_EN) {
this.homePageUNID_EN = homePageUNID_EN;
}
public String getAppEmailAddress() {
return appEmailAddress;
}
public void setAppEmailAddress(String appEmailAddress) {
this.appEmailAddress = appEmailAddress;
}
public String getSystemMessageFR() {
return systemMessageFR;
}
public void setSystemMessageFR(String systemMessageFR) {
this.systemMessageFR = systemMessageFR;
}
public String getSystemMessageEN() {
return systemMessageEN;
}
public void setSystemMessageEN(String systemMessageEN) {
this.systemMessageEN = systemMessageEN;
}
public void setStatsDB(String statsDB) {
this.statsDB = statsDB;
}
public String getStatsDB() {
return statsDB;
}
public void setDefaultLang(String defaultLang) {
this.defaultLang = defaultLang;
}
public String getDefaultProv() {
return defaultProv;
}
public void setDefaultProv(String defaultPRov) {
this.defaultProv = defaultPRov;
}
public void setShowProv(String showProv) {
this.showProv = showProv;
}
public String getShowProv() {
return showProv;
}
public String getDefaultLang() {
return defaultLang;
}
public String getMessageIntro() {
return messageIntro;
}
public void setMessageIntro(String messageIntro) {
this.messageIntro = messageIntro;
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getAppURL() {
return appURL;
}
public void setAppURL(String appURL) {
this.appURL = appURL;
}
public String getEmailText() {
return emailText;
}
public void setEmailText(String emailText) {
this.emailText = emailText;
}
public String getClickLinkText() {
return clickLinkText;
}
public void setClickLinkText(String clickLinkText) {
this.clickLinkText = clickLinkText;
}
public String getEmailFooter() {
return emailFooter;
}
public void setEmailFooter(String emailFooter) {
this.emailFooter = emailFooter;
}
//allowRatingModification
public String getAllowRatingModification() {
return allowRatingModification;
}
public void setAllowRatingModification(String allowRatingModification) {
this.allowRatingModification = allowRatingModification;
}
}
The VariableResolver goes through all implicit variables (e.g. session, database) as well as scoped variables (e.g. applicationScope.myVar). Your bean is also accessed from SSJS via the VariableResolver.
So you can use:
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "myAppScopeBean");
This is not a direct answer to your question...
An alternative would be to set the value you want in applicationScope and then access it this way from your bean. To access the entire bean directly is a different answer.
You use this code get a handle to your applicationScope.
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map<String, Object> applicationScope = externalContext.getApplicationMap();
Then to use this you have code like this:
String agentLogDB = (String) applicationScope.get("LOGDB");

how to generate sequence number using c# in window application

private string GenerateID()
{
}
private void auto()
{
AdmissionNo.Text = "A-" + GenerateID();
}
with prefix of A like below
A-0001
A-0002 and so on .
You can use below code.
private string GenerateId()
{
int lastAddedId = 8; // get this value from database
string demo = Convert.ToString(lastAddedId + 1).PadLeft(4, '0');
return demo;
// it will return 0009
}
private void Auto()
{
AdmissionNo.Text = "A-" + GenerateId();
// here it will set the text as "A-0009"
}
Look at this
public class Program
{
private static int _globalSequence;
static void Main(string[] args)
{
_globalSequence = 0;
for (int i = 0; i < 10; i++)
{
Randomize(i);
Console.WriteLine("----------------------------------------->");
}
Console.ReadLine();
}
static void Randomize(int seed)
{
Random r = new Random();
if (_globalSequence == 0) _globalSequence = r.Next();
Console.WriteLine("Random: {0}", _globalSequence);
int localSequence = Interlocked.Increment(ref _globalSequence);
Console.WriteLine("Increment: {0}, Output: {1}", _globalSequence, localSequence);
}
}
Whether it is an windows application or not is IMHO not relevant. I'd rather care about thread safety. Hence, I would use something like this:
public sealed class Sequence
{
private int value = 0;
public Sequence(string prefix)
{
this.Prefix = prefix;
}
public string Prefix { get; }
public int GetNextValue()
{
return System.Threading.Interlocked.Increment(ref this.value);
}
public string GetNextNumber()
{
return $"{this.Prefix}{this.GetNextValue():0000}";
}
}
This could easily be enhanced to use the a digit count. So the "0000" part could be dynamically specified as well.

Trying to create a package for my java application

I am in the process of putting together a simple RPG game engine in java. At this point everything works fine while all my classes are in one directory. Basically, I know I am going to end up with a heap of files and wish to organise them into a package structure. I followed the directions at http://www.jarticles.com/package/package_eng.html but can't seem to make the magic happen. The two classes posted are the least dependent of the lot and I figure if I can get these working then the rest shouldn't be a drama. For the record I am using openJDK in Leeenux (remix of Ubuntu netbook Remix)
First class
package adventure.engine;
import java.util.*;
public class Inventory
{
ArrayList itemList = new ArrayList();
public Inventory()
{
}
public void addItem()
{
}
public void removeItem()
{
}
}
And the second:
package adventure.engine;
import adventure.engine.*;
public class PlayerCharacter
{
private String name = "Player";
private String race;
private String plrClass;
private int level;
private int xp;
private int levelXp;
private Inventory inventory = new Inventory();
//---------
//Abilities
//---------
private static final String[] abilitiesList = {"Strength",
"Dexterity",
"Constitution",
"Intelligence",
"Wisdom",
"Charisma"};
private int[] abilitiesValues = new int[abilitiesList.length];
//------
//Skills
//------
private static final String[] skillsList = {"Acrobatics" , "Insight",
"Arcana" , "Intimidate",
"Athletics" , "Nature",
"Bluff" , "Perception",
"Diplomacy" , "Religion",
"Dungeoneering" , "Stealth",
"Endurance" , "Streetwise",
"Heal" , "Thievery",
"History"};
private int[] skillsValues = new int[skillsList.length];
//***********
//Constructor
//***********
public PlayerCharacter()
{
level = 1;
xp = 0;
levelXp = 1000;
setAbility("Strength", 8);
setAbility("Dexterity", 10);
setAbility("Constitution", 10);
setAbility("Intelligence", 10);
setAbility("Wisdom", 10);
setAbility("Charisma", 10);
} //public PlayerSheet()
//*************
//Class Methods
//*************
public void addXp(int val)
{
xp += val;
if (xp >= levelXp)
{
level++;
xp -= levelXp;
//levelXp += ;
}
} //public void addXp(int val)
public void updateSkills()
{
}
//Mutators
public void setName(String n)
{
name = n;
}
public void setLevel(int l)
{
level = l;
}
public void setRace(String r)
{
race = r;
}
public void setXP(int x)
{
xp = x;
}
public void setClass(String c)
{
plrClass = c;
}
//set ability value by name
public void setAbility(String a, int val)
{
for(int i = 0; i < abilitiesList.length; i++)
{
if(abilitiesList[i].compareTo(a) == 0)
{
abilitiesValues[i] = val;
}
}
}
//set ability by index
public void setAbility(int index, int val)
{
abilitiesValues[index] = val;
}
//set skill by name
public void setSkill(String name, int val)
{
for(int i = 0; i < skillsList.length; i++)
{
if(skillsList[i].compareTo(name) == 0)
{
skillsValues[i] = val;
}
}
}
//set skill by index
public void setSkill(int index, int val)
{
skillsValues[index] = val;
}
//Accessors
public static String[] getAbilityList()
{
return abilitiesList;
}
public static String[] getSkillsList()
{
return skillsList;
}
//retrieve an ability value by name
public int getAbility(String a)
{
int val = 0;
for(int i = 0; i < abilitiesList.length; i++)
{
if(abilitiesList[i].compareTo(a) == 0)
{
val = abilitiesValues[i];
break;
}
}
return val;
}
//retrieve an ability value by index number
public int getAbility(int i)
{
return abilitiesValues[i];
}
public int getSkill(String s)
{
int val = 0;
for(int i = 0; i < skillsList.length; i++)
{
if(skillsList[i].compareTo(s) == 0)
{
val = skillsValues[i];
break;
}
}
return val;
}
public int getSkill(int i)
{
return skillsValues[i];
}
public String getName()
{
return name;
}
public String getRace()
{
return race;
}
public String getPlrClass()
{
return plrClass;
}
public int getLevel()
{
return level;
}
public int getXP()
{
return xp;
}
public int getLevelXP()
{
return levelXp;
}
} //public class PlayerCharacter
Classes reside in /home/user/Java/adventure/engine
Output from echo $classpath is /home/james/Java:/.:
when I attempt to compile the second class I get the following error:
PlayerCharacter.java:18: cannot find symbol
symbol : class Inventory
location: class adventure.engine.PlayerCharacter
private Inventory inventory = new Inventory();
^
PlayerCharacter.java:18: cannot find symbol
symbol : class Inventory
location: class adventure.engine.PlayerCharacter
private Inventory inventory = new Inventory();
Any feedback on this would be greatly appreciated.How to solve this?
Two things.
1) You might not have compiled Inventory
2) PlayerCharacter and Inventory are in same package. So there is no need to import.
You should be compiling them as
javac adventure/engine/Inventory.java
javac adventure/engine/PlayerCharacter.java

Why does this Dialog immediately dispose in this situation?

There is a user defined component , derived from Container, inside my Form. It has a pointerPressed method implemented in its class code. In the code of that method I show a Dialog containing a List , and in the class code of the derived Dialog ( in the constructor ) I set the setDisposeWhenPointerOutOfBounds method with the argument value to true.
The problem is that in run time when I click the user defined component ( ListBox ) in my Form then the Dialog is shown , of course , but immediately it closes ( disposes ) , although I don't click outside the boundary of the Dialog !
So why does it have such a behavior ?
Codes :
public class ListBox extends Container
{
private Form containerForm;
private Container cListBox = new Container(new BorderLayout());
private Label[] tLabel;
private int[] tLabelW;
private int largestLabelW;
private Label libelle = new Label();
private Label arrow = new Label((MenuPrincipalForm.r).getImage("listboxarrow"));
private int preferredWidth, preferredHeight, screenWidth, screenHeight;
private Vector vData = new Vector();
private final int leftPadding = 3;
private int listW;
private List list;
private DialogListBox dialog;
private String selectedData;
public ListBox(Form containingForm, String[] lData, int prefHeight, int formWidth, int formHeight, int topMargin, int bottomMargin)
{
super(new FlowLayout(Component.CENTER));
setFocusable(true);
containerForm = containingForm;
screenWidth = formWidth;
screenHeight = formHeight;
tLabel = new Label[lData.length + 1];
tLabelW = new int[lData.length + 1];
if (lData.length > 0)
{
for (int i = 0 ; i < lData.length + 1 ; i++)
{
if (i < lData.length)
{
vData.addElement(new String(lData[i]));
tLabel[i] = new Label(lData[i]);
tLabelW[i] = tLabel[i].getPreferredW();
}
else
{
vData.addElement(new String(""));
tLabel[i] = new Label("");
tLabelW[i] = 0;
}
}
}
else
{
vData.addElement(new String(""));
tLabel[0] = new Label("");
tLabelW[0] = 0;
}
largestLabelW = Comparator.max(tLabelW);
preferredWidth = leftPadding + largestLabelW + arrow.getPreferredW();
preferredHeight = prefHeight - 2 ;
selectedData = String.valueOf(vData.lastElement());
libelle.setText(String.valueOf(vData.lastElement()));
libelle.setTextPosition(Label.LEFT);
libelle.setPreferredW(preferredWidth);
libelle.setPreferredH(preferredHeight);
arrow.setAlignment(Label.CENTER);
arrow.setPreferredH(preferredHeight);
dialog = new DialogListBox(leftPadding, this);
list = dialog.getList();
cListBox.addComponent(BorderLayout.WEST, libelle);
cListBox.addComponent(BorderLayout.EAST, arrow);
cListBox.setPreferredH(preferredHeight);
getUnselectedStyle().setPadding(Component.LEFT, leftPadding);
getSelectedStyle().setPadding(Component.LEFT, leftPadding);
getUnselectedStyle().setBorder(Border.createLineBorder(1));
getSelectedStyle().setBorder(Border.createLineBorder(1));
addComponent(cListBox);
setPreferredH(preferredHeight);
getUnselectedStyle().setMargin(Component.TOP, topMargin);
getSelectedStyle().setMargin(Component.TOP, topMargin);
getUnselectedStyle().setMargin(Component.BOTTOM, bottomMargin);
getSelectedStyle().setMargin(Component.BOTTOM, bottomMargin);
}
public void setSelectedIndex(int idx)
{
list.setSelectedIndex(idx);
selectedData = String.valueOf(vData.elementAt(idx));
libelle.setText(String.valueOf(vData.elementAt(idx)));
repaint();
}
public void setSelectedData(String data)
{
selectedData = data;
libelle.setText(selectedData);
repaint();
}
public String getSelectedData()
{
return selectedData;
}
public int getLastIndex()
{
return vData.indexOf(vData.lastElement());
}
public Vector getListBoxDataSource()
{
return vData;
}
private void showListBoxDialog()
{
int espaceVertRestant, top, bottom, left, right;
espaceVertRestant = screenHeight - ( libelle.getAbsoluteY() + preferredHeight );
if (espaceVertRestant > list.getPreferredH())
{
top = getAbsoluteY() + preferredHeight - 1 ;
bottom = screenHeight - ( getAbsoluteY() + preferredHeight + list.getPreferredH() ) ;
}
else
{
top = screenHeight - ( list.getPreferredH() + preferredHeight + espaceVertRestant ) ;
bottom = getAbsoluteY() - 1 ;
}
left = getAbsoluteX() ;
right = screenWidth - ( getAbsoluteX() + getPreferredW() );
listW = screenWidth - left - right ;
containerForm.setTintColor(containerForm.getSelectedStyle().getBgColor());
dialog.setListW(listW);
dialog.show(top, bottom, left, right, false, false);
}
public void keyPressed(int keyCode)
{
int gameAction = (Display.getInstance()).getGameAction(keyCode);
if (gameAction == Display.GAME_FIRE)
showListBoxDialog();
else
super.keyPressed(keyCode);
}
public void pointerPressed(int x, int y)
{
showListBoxDialog();
}
}
public class DialogListBox extends Dialog implements ActionListener
{
private Vector vData;
private CListCellListBox listRenderer;
private List list;
private ListBox theListBox;
public DialogListBox(int leftPadding, ListBox listBox)
{
super();
setFocusable(true);
setDisposeWhenPointerOutOfBounds(true);
getContentPane().getSelectedStyle().setPadding(0, 0, 0, 0);
getContentPane().getUnselectedStyle().setPadding(0, 0, 0, 0);
getContentPane().getStyle().setPadding(0, 0, 0, 0);
theListBox = listBox;
listRenderer = new CListCellListBox(false);
vData = listBox.getListBoxDataSource();
list = (new CList(vData, false)).createList(listRenderer, this);
list.setItemGap(0);
list.setSelectedIndex(vData.indexOf(vData.lastElement()));
list.getSelectedStyle().setPadding(0, 0, leftPadding, 0);
list.getUnselectedStyle().setPadding(0, 0, leftPadding, 0);
list.getUnselectedStyle().setBorder(Border.createLineBorder(1), false);
list.getSelectedStyle().setBorder(Border.createLineBorder(1), false);
list.setIsScrollVisible(false);
addComponent(list);
}
protected void onShow()
{
list.requestFocus();
repaint();
}
public void setListW(int prefW)
{
list.setPreferredW(prefW);
}
public List getList()
{
return list;
}
private void refreshListBox()
{
dispose();
if (list.getSelectedItem() instanceof Content)
{
Content valeur = (Content)list.getSelectedItem();
theListBox.setSelectedData(valeur.getEnreg());
}
}
public void keyPressed(int keyCode)
{
int gameAction = (Display.getInstance()).getGameAction(keyCode);
if (gameAction == Display.GAME_FIRE)
refreshListBox();
else
super.keyPressed(keyCode);
}
public void actionPerformed(ActionEvent ae) {
if ( (ae.getSource() instanceof List) && ((List)ae.getSource()).equals(list) )
refreshListBox();
}
}
public class CList {
private Vector data = new Vector();
private boolean showPhoto;
private Content[] contents;
public CList(Vector vData, boolean displayPhoto)
{
data = vData;
showPhoto = displayPhoto;
contents = new Content[vData.size()];
}
public List createList(CListCell renderer, ActionListener listener)
{
List theList;
if (showPhoto)
{
for(int i = 0; i < data.size(); i++)
{
Image img = getFirstImage(Formatage.getColumnValueAt(String.valueOf(data.elementAt(i)), 0));
contents[i] = new Content(img, String.valueOf(data.elementAt(i)));
}
}
else
{
for(int i = 0; i < data.size(); i++)
{
contents[i] = new Content(String.valueOf(data.elementAt(i)));
}
}
theList = new List(contents);
theList.setListCellRenderer(renderer);
theList.setFixedSelection(List.FIXED_NONE_CYCLIC);
theList.addActionListener(listener);
return theList;
}
// ... other methods
}
You should always use pointerReleased/keyReleased for navigation to different forms/dialogs.
Otherwise the pointer/key released will be sent to the next form/dialog and trigger an action there.
Pointer pressed is mostly used internally in LWUIT and for some special cases.

Resources