Travesring through an object in java - java

I have a method that return an object of a class.The object sets the properties of class and returns.
I have to traverse the object and get the value of the properties which the object has set before.
I tried to use for-each loop,iterator but failed to traverse.
Can someone please help me to get through this.Thanks in advance.
code:
public class ConsumerTool {
public MessageBean getMessages() {
MessageBean msgBean = new MessageBean();
msgBean.setAtmId(atmId.trim());
msgBean.setEventText(eventText.trim());
msgBean.setEventNumber(eventNumber.trim());
msgBean.setSeverity(severity.trim());
msgBean.setSubsystemID(subsystemID.trim());
msgBean.setUniqueEventID(uniqueEventID.trim());
msgBean.setTaskID(taskID.trim());
msgBean.setGenerator(generator.trim());
msgBean.setGeneratorBuildVsn(generatorBuildVsn.trim());
msgBean.setDateTime(dateTime.trim());
this.msgBean = msgBean;
return msgBean;
}
}
JavaBean class:
public class MessageBean implements java.io.Serializable {
public String dateTime;
public String severity;
public String eventText;
public String eventNumber;
public String generator;
public String generatorBuildVsn;
public String atmId;
public String uniqueEventID;
public String subsystemID;
public String taskID;
//System.out.println("dateTime2222222"+dateTime);
public String getAtmId() {
return this.atmId;
}
public void setAtmId(String n) {
this.atmId = n;
}
public String getDateTime() {
return this.dateTime;
}
public void setDateTime(String n) {
this.dateTime = n.trim();
}
public String getEventNumber() {
return this.eventNumber;
}
public void setEventNumber(String n) {
this.eventNumber = n;
}
public String getEventText() {
return this.eventText;
}
public void setEventText(String n) {
this.eventText = n;
}
public String getGenerator() {
return this.generator;
}
public void setGenerator(String n) {
this.generator = n;
}
public String getGeneratorBuildVsn() {
return this.generatorBuildVsn;
}
public void setGeneratorBuildVsn(String n) {
this.generatorBuildVsn = n;
}
public String getSeverity() {
return this.severity;
}
public void setSeverity(String n) {
this.severity = n;
}
public String getSubsystemID() {
return this.subsystemID;
}
public void setSubsystemID(String n) {
this.subsystemID = n;
}
public String getTaskID() {
return this.taskID;
}
public void setTaskID(String n) {
this.taskID = n;
}
public String getUniqueEventID() {
return this.uniqueEventID;
}
public void setUniqueEventID(String n) {
this.uniqueEventID = n;
}
}
The theme is the object sets the properties of javabean class and I have to get those values from UI.
In Jsp
<%
MessageBean consumer = msg.getMessages();
//Now here i want to iterate that consumer object
%>

As the MessagesBean seems to comply the javabeans specification, you can just use java.beans.Introspector for this.
MessageBean messageBean = consumerTool.getMessages();
// ...
BeanInfo beanInfo = Introspector.getBeanInfo(MessageBean.class);
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
String name = property.getName();
Object value = property.getReadMethod().invoke(messageBean);
System.out.println(name + "=" + value);
}
This all is under the covers using the reflection API.
Update your edit reveals that you're intending to use this to present the data in JSP. This is then not really the right approach. Bite the bullet and specify every property separately. This way you've full control over the ordering.

Related

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());
}});

Android java loop through object list

My code connects to an Api, takes all Json values and stores them all in a object list resultClass. How I loop through the list and display all name properties of the objects?
This is the code I am using. The JSON values are sent with the method call as parameter with name object. Then loops and takes all objects and stores them in a list.
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
resultClass.setData_id(resultsObject
.getInt("data_id"));
resultClass.setName(resultsObject
.getString("name"));
resultClass.setRarity(resultsObject
.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject
.getString("img"));
resultClass.setType_id(resultsObject
.getInt("type_id"));
resultClass.setSub_type_id(resultsObject
.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < resultClass.total; i++) {
Log.i("gw2Log", resultClass.name[i]);
}
}
This is the Json response i am logging
Json Response{"total":6,"last_page":1,"results":[{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/01D07FABAE26C0E5240892B00DA7AF90AB0EA022\/455828.png","rarity":7,"type_id":16,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":19648,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Gift of Twilight","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/CE3AF0B7B9BB6244726779F5B6A930541BA6C15F\/456031.png","rarity":5,"type_id":18,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":49191,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight","min_sale_unit_price":0,"restriction_level":80,"sub_type_id":6},{"sale_availability":23,"offer_availability":20643,"img":"https:\/\/render.guildwars2.com\/file\/CE3AF0B7B9BB6244726779F5B6A930541BA6C15F\/456031.png","rarity":7,"type_id":18,"sale_price_change_last_hour":0,"max_offer_unit_price":27500000,"data_id":30704,"price_last_changed":"2015-04-20 20:17:57 UTC","offer_price_change_last_hour":0,"name":"Twilight","min_sale_unit_price":31959998,"restriction_level":80,"sub_type_id":6},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/D04EF6FDE3DBC26E7BB109EB4F52057FEAD8619E\/699325.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65578,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Armor Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/666209104CCB024D53359C0EA0A299076E610771\/65704.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65577,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Token Loot Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/2626184EDDC254B4F7634A04F878062C6B2AF20D\/780372.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65579,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Weapons Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0}],"count":6,"page":1}
When digging around for a solution and checking the actual error it says it expects and array but a string is given Log.i("gw2Log", resultClass.name[i]);
When I loop through this Log call Log.i("gw2Log", resultClass.name); it displays the last objects name property the amount it loops.
EDIT:
On request to include my resultClass.java:
public class resultClass {
public int data_id;
public String name;
public int rarity;
public int restriction_level;
public String img;
public int type_id;
public int sub_type_id;
public String price_last_changed;
public int max_offer_unit_price;
public int min_sale_unit_price;
public int offer_availability;
public int sale_availability;
public int sale_price_change_last_hour;
public int offer_price_change_last_hour;
public int count;
public int page;
public int last_page;
public int total;
public int getData_id() {
return data_id;
}
public void setData_id(int data_id) {
this.data_id = data_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRarity() {
return rarity;
}
public void setRarity(int rarity) {
this.rarity = rarity;
}
public int getRestriction_level() {
return restriction_level;
}
public void setRestriction_level(int restriction_level) {
this.restriction_level = restriction_level;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getSub_type_id() {
return sub_type_id;
}
public void setSub_type_id(int sub_type_id) {
this.sub_type_id = sub_type_id;
}
public String getPrice_last_changed() {
return price_last_changed;
}
public void setPrice_last_changed(String price_last_changed) {
this.price_last_changed = price_last_changed;
}
public int getMax_offer_unit_price() {
return max_offer_unit_price;
}
public void setMax_offer_unit_price(int max_offer_unit_price) {
this.max_offer_unit_price = max_offer_unit_price;
}
public int getMin_sale_unit_price() {
return min_sale_unit_price;
}
public void setMin_sale_unit_price(int min_sale_unit_price) {
this.min_sale_unit_price = min_sale_unit_price;
}
public int getOffer_availability() {
return offer_availability;
}
public void setOffer_availability(int offer_availability) {
this.offer_availability = offer_availability;
}
public int getSale_availability() {
return sale_availability;
}
public void setSale_availability(int sale_availability) {
this.sale_availability = sale_availability;
}
public int getSale_price_change_last_hour() {
return sale_price_change_last_hour;
}
public void setSale_price_change_last_hour(int sale_price_change_last_hour) {
this.sale_price_change_last_hour = sale_price_change_last_hour;
}
public int getOffer_price_change_last_hour() {
return offer_price_change_last_hour;
}
public void setOffer_price_change_last_hour(int offer_price_change_last_hour) {
this.offer_price_change_last_hour = offer_price_change_last_hour;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLast_page() {
return last_page;
}
public void setLast_page(int last_page) {
this.last_page = last_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
try something like this
first make a new object something like MyObject
public class MyObject {
public int data_id;
public String name;
public int rarity;
public int restriction_level;
public String img;
public int type_id;
public int sub_type_id;
public String price_last_changed;
public int max_offer_unit_price;
public int min_sale_unit_price;
public int offer_availability;
public int sale_availability;
public int sale_price_change_last_hour;
public int offer_price_change_last_hour;
public int getData_id() {
return data_id;
}
public void setData_id(int data_id) {
this.data_id = data_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRarity() {
return rarity;
}
public void setRarity(int rarity) {
this.rarity = rarity;
}
public int getRestriction_level() {
return restriction_level;
}
public void setRestriction_level(int restriction_level) {
this.restriction_level = restriction_level;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getSub_type_id() {
return sub_type_id;
}
public void setSub_type_id(int sub_type_id) {
this.sub_type_id = sub_type_id;
}
public String getPrice_last_changed() {
return price_last_changed;
}
public void setPrice_last_changed(String price_last_changed) {
this.price_last_changed = price_last_changed;
}
public int getMax_offer_unit_price() {
return max_offer_unit_price;
}
public void setMax_offer_unit_price(int max_offer_unit_price) {
this.max_offer_unit_price = max_offer_unit_price;
}
public int getMin_sale_unit_price() {
return min_sale_unit_price;
}
public void setMin_sale_unit_price(int min_sale_unit_price) {
this.min_sale_unit_price = min_sale_unit_price;
}
public int getOffer_availability() {
return offer_availability;
}
public void setOffer_availability(int offer_availability) {
this.offer_availability = offer_availability;
}
public int getSale_availability() {
return sale_availability;
}
public void setSale_availability(int sale_availability) {
this.sale_availability = sale_availability;
}
public int getSale_price_change_last_hour() {
return sale_price_change_last_hour;
}
public void setSale_price_change_last_hour(int sale_price_change_last_hour) {
this.sale_price_change_last_hour = sale_price_change_last_hour;
}
public int getOffer_price_change_last_hour() {
return offer_price_change_last_hour;
}
public void setOffer_price_change_last_hour(int offer_price_change_last_hour) {
this.offer_price_change_last_hour = offer_price_change_last_hour;
}
}
then make your resultClass look like this
public class resultClass {
public int count;
public int page;
public int last_page;
public int total;
public ArrayList<MyObject> myObjects = new ArrayList();
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLast_page() {
return last_page;
}
public void setLast_page(int last_page) {
this.last_page = last_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public MyObject getObject(int pos){
return myObjects.get(pos);
}
public void addObject(MyObject object)
{
myObjects.add(object);
}
}
then your response should be something like this
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
MyObject temp = new MyObject();
temp.setData_id(resultsObject
.getInt("data_id"));
temp.setName(resultsObject
.getString("name"));
temp.setRarity(resultsObject
.getInt("rarity"));
temp.setRestriction_level(resultsObject
.getInt("restriction_level"));
temp.setImg(resultsObject
.getString("img"));
temp.setType_id(resultsObject
.getInt("type_id"));
temp.setSub_type_id(resultsObject
.getInt("sub_type_id"));
temp.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
temp.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
temp.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
temp.setOffer_availability(resultsObject
.getInt("offer_availability"));
temp.setSale_availability(resultsObject
.getInt("sale_availability"));
temp.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
temp.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
resultClass.addObject(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < resultClass.total; i++) {
Log.i("gw2Log", resultClass.getObject(i).name);
}
}
You could try this code. You wanted to use table of objects, but you created just single object. Create arrayList of your resultClass and then use simplier 'for' for your list
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
List<resultClass> resultClassList = new ArrayList<resultClass>();
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
resultClass.setData_id(resultsObject
.getInt("data_id"));
resultClass.setName(resultsObject
.getString("name"));
resultClass.setRarity(resultsObject
.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject
.getString("img"));
resultClass.setType_id(resultsObject
.getInt("type_id"));
resultClass.setSub_type_id(resultsObject
.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
resultClassList.add(resultClass);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(resultClass result : resultClassList) {
Log.i("gw2Log", result.name);
}
}
Ok, I'm pretty sure of several things:
Tomer Shemesh is right, you are overriding your resultClass object on every iteration.
You wanna make arrays out of your normal variables in the resultClass so you can actually store more than one Item.
About that error you're getting:
It occurs in the lower for loop, where you want to log the names, right?
resultClass.nameis a String variable, it holds exactly one string of characters. You are trying to get a string out of an array by saying something like resultClass.name[i]. For that to work youu need to decrlare it as a string array, holding several string like public String[] name;, and in the constructor initialize it with a given capactiy like name = new String[cap];. Or you use an ArrayList<String> instead, which grows dynmically, but uses own getters and setters instead of the easy name[index] functions of an array.
Sorry, but I don't really want to write the right code here, as pretty much the whole thing needs to be rewritten, I hope this will help you rewrite it yourself though.

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

Inner Class. What is its purpose?

Can someone tell me what the purpose of having inner classes? I can think of a few but may be they are not good reasons for using inner classes. My reasoning is that inner class is helpful when you want to use a class that no other classes can use. What else?
When I was learning Java we used inner classes for GUI event handling classes. It is sort of a "one time use" class that need not be available to other classes, and only is relevant to the class in which it resides.
Inner classes can be used to simulate closures: http://en.wikipedia.org/wiki/Closure_(computer_science)#Java
I use inner classes to define a structure that is best represented by the containing class, but doesn't necessarily make sense to use a separate external class to represent the structure.
To give an example I have a class that represents a particular type of network device, and the class has certain types of tests that can be run on that device. For each test there is also a potential set of errors that can be found. Each type of device may have a different structure for the errors.
With this you could do things like
List<Error> errors = RemoteDeviceA.getErrors();
With methods being available from the inner class, like
for ( Error error : errors ) {
System.out.println("MOnitor Type: " + error.getMonType());
...
}
Of course there are other ways to do this, this is just an inner class approach.
Simplified (aka incomplete) code for above:
public class RemoteDeviceA {
private String host;
private String user;
private String password;
private static List<Error> errors;
public RemoteDeviceA(String user, String host, String password) {
this.host = host;
this.user = user;
this.password = password;
login();
}
private void login() {
// Logs in
}
public void runTestA() {
List<Error> errorList = new ArrayList<Error>();
//loop through test results
if (!value.equals("0")) {
Error error = new Error(node, rackNum, shelfNum, slotNum, monType, value);
if (error.isError()) {
errorList.add(error);
}
}
setErrors(errorList);
}
private static void setErrors(List<Error> errors) {
RemoteDeviceA.errors = errors;
}
public List<Error> getErrors() {
return errors;
}
public class Error {
private String monType;
private String node;
private String rack;
private String shelf;
private String slot;
private String value;
private boolean error = false;
private boolean historyError = false;
private boolean critical = false;
private boolean criticalHistory = false;
Error(String node, String rack, String shelf, String slot,
String monType, String value) {
parseAlarm(node, rack, shelf, slot, monType, value);
}
private void parseAlarm(String node, String rack, String shelf,
String slot, String monType, String value) {
String modType = "";
if (monType.startsWith("ES_15") && !value.equals("0")) {
setMonType("ES_15");
setError(true);
} else if (monType.startsWith("SES_15") && !value.equals("0")) {
setMonType("SES_15");
setError(true);
} else if (monType.startsWith("BBE_15") && !value.equals("0")) {
setMonType("BBE_15");
setError(true);
} else if (monType.startsWith("UT_15") && !value.equals("0")) {
setMonType("UT_15");
setError(true);
setCritial(critical);
} else if (monType.startsWith("ES_24") && !value.equals("0")) {
setMonType("ES_24");
setHistoryError(true);
setError(true);
} else if (monType.startsWith("SES_24") && !value.equals("0")) {
setMonType("SES_24");
setHistoryError(true);
setError(true);
} else if (monType.startsWith("BBE_24") && !value.equals("0")) {
setMonType("BBE_24");
setHistoryError(true);
setError(true);
} else if (monType.startsWith("UT_24") && !value.equals("0")) {
setMonType("UT_24");
setHistoryError(true);
setError(true);
setCriticalHistory(true);
} else if (monType.startsWith("UT_15") && !value.equals("0")) {
setMonType("UT_15");
setError(true);
setCritial(true);
} else if (monType.startsWith("LASPWR")) {
float laserPwr = Float.valueOf(value);
if (node.startsWith("LEM_EM")) {
if ((laserPwr < 8.0) || (laserPwr > 12.0)) {
setMonType("LASERPWR");
setError(true);
}
} else if (node.startsWith("LEM10")) {
if ((laserPwr < 18.0) || (laserPwr > 22.0)) {
setMonType("LASERPWR");
setError(true);
}
}
}
if (isError()) {
setNode(node);
setRack(rack);
setShelf(shelf);
setSlot(slot);
setValue(value);
setError(true);
}
}
private void setMonType(String monType) {
this.monType = monType;
}
public String getMonType() {
return monType;
}
private void setNode(String node) {
this.node = node;
}
public String getNode() {
return node;
}
public void setRack(String rack) {
this.rack = rack;
}
public String getRack() {
return rack;
}
public void setShelf(String shelf) {
this.shelf = shelf;
}
public String getShelf() {
return shelf;
}
public void setSlot(String slot) {
this.slot = slot;
}
public String getSlot() {
return slot;
}
private void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
private void setError(boolean error) {
this.error = error;
}
public boolean isError() {
return error;
}
public void setCritial(boolean critical) {
this.critical = critical;
}
public boolean isCritical() {
return critical;
}
public void setCriticalHistory(boolean criticalHistory) {
this.criticalHistory = criticalHistory;
}
public boolean isCriticalHistory() {
return criticalHistory;
}
public void setHistoryError(boolean historyError) {
this.historyError = historyError;
}
public boolean isHistoryError() {
return historyError;
}
}
}
A list implementation that internally uses a linked list to store the elements could make good use of an inner class to represent the nodes within the list. I think you've hit the nail on the head by saying that you'd use such a class where you want to use it internally to a class but don't want it exposed - a 'one off' class that is only really useful 'here'.
I use inner classes (in C++) in situations where multiple classes, unrelated through inheritance, have conceptually similar implementation details, which form an implicit part of the public interface and ought to be named similarly.
class lib::Identifier { ... };
class lib::Person {
public:
class Identifier : public lib::Identifier { ... };
};
class lib::File {
public:
class Identifier : public lib::Identifier { ... };
};
This makes it convenient to refer to Identifier, Person::Identifier, and File::Identifier as simply Identifier, in the appropriate scopes.

html:text tag not working

I have a form that looks somewhat like this:
public class MaintainForecastInputForm extends ActionForm {
private MainMenuForm mainMenuForm = new MainMenuForm();
public SelectProdLineAssociationForm selectProdLineAssociationForm = new SelectProdLineAssociationForm();
private EconometricDataForm econometricDataForm = new EconometricDataForm();
private EconometricImportDownloadForm econometricImportDownloadForm = new EconometricImportDownloadForm();
private String userAction;
private List<MaintainForecastInputForm.DemandForecast> demands = new ArrayList<MaintainForecastInputForm.DemandForecast>();
private List<MaintainForecastInputForm.DemandForecast> forecasts = new ArrayList<MaintainForecastInputForm.DemandForecast>();
private DemandForecast iimsForecast = new DemandForecast();
private DemandForecast econometricForecast = new DemandForecast();
public static class DemandForecast {
private String subType;
private String shortTermWtAvg="0.0";
private String midTermWtAvg="0.0";
private String longTermWtAvg="0.0";
private String shortTermPct="0.0";
private String midTermPct="0.0";
private String longTermPct="0.0";
private List yearDemands = new ArrayList();
public static class Year {
private String fyTotalValue="0.0";
private String fyPctChange="0.0";
private List monthDemands = new ArrayList();
public String getFyPctChange() {
return fyPctChange;
}
public void setFyPctChange(String fyPctChange) {
this.fyPctChange = fyPctChange;
}
public String getFyTotalValue() {
return fyTotalValue;
}
public void setFyTotalValue(String fyTotalValue) {
this.fyTotalValue = fyTotalValue;
}
} // Year
public static class Month {
private String demandValue="0.0";
private String demandQuantity="0.0";
public String getDemandQuantity() {
return demandQuantity;
}
public void setDemandQuantity(String demandQuantity) {
this.demandQuantity = demandQuantity;
}
public String getDemandValue() {
return demandValue;
}
public void setDemandValue(String demandValue) {
this.demandValue = demandValue;
}
} // Month
public String getLongTermPct() {
return longTermPct;
}
public void setLongTermPct(String longTermPct) {
this.longTermPct = longTermPct;
}
public String getLongTermWtAvg() {
return longTermWtAvg;
}
public void setLongTermWtAvg(String longTermWtAvg) {
this.longTermWtAvg = longTermWtAvg;
}
public String getMidTermPct() {
return midTermPct;
}
public void setMidTermPct(String midTermPct) {
this.midTermPct = midTermPct;
}
public String getMidTermWtAvg() {
return midTermWtAvg;
}
public void setMidTermWtAvg(String midTermWtAvg) {
this.midTermWtAvg = midTermWtAvg;
}
public String getShortTermPct() {
return shortTermPct;
}
public void setShortTermPct(String shortTermPct) {
this.shortTermPct = shortTermPct;
}
public String getShortTermWtAvg() {
return shortTermWtAvg;
}
public void setShortTermWtAvg(String shortTermWtAvg) {
this.shortTermWtAvg = shortTermWtAvg;
}
public String getSubType() {
return subType;
}
public void setSubType(String subType) {
this.subType = subType;
}
public List getYearDemands() {
return yearDemands;
}
public void setYearDemands(List yearDemands) {
this.yearDemands = yearDemands;
}
} // DemandForecast
}
and in my JSP I have the following:
<c:forEach items="${form.iimsForecast.yearDemands}" var="yearDemand" varStatus="year">
<tr>
<td>${yearDemand.fiscalYear}</td>
<c:forEach items="${yearDemand.monthDemands}" var="yearMonth" varStatus="month">
<c:choose>
<c:when test="${year.count == 1 && month.count < yearDemand.currentMonth}">
<td class="lightShaded dmnd">
<html-el:text property="form.iimsForecast.yearDemands.monthDemands.demandValue">
</td>
...
I'm getting a JSP exception - getter property is not been found in the form although it is there. Can somebody help me with this problem please?
Your code does not show whether you have a getIimsForecast() method on your form (it only shows iimsForecast property) - if you don't, you need to add it. However, that's not the only problem.
Your property path includes yearDemands and monthDemands and getter methods for both return Lists. That's illegal - nested property path must either have single beans or have indexed access for list elements (e.g. iimsForecast.yearDemands[0].monthDemands[0].demandValue).
Finally, you probably don't need to prefix your property path with form, although that depends on your configuration and whether you have an enclosing <html:form> tag.
This may sound obvious, but did you add the tag library to the page?
<%# taglib prefix="html" uri="http://struts.apache.org/tags-html-el" %>

Categories

Resources