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.
Related
**In this i am trying to sort an array of objects by their id's whose age > 30 but compiler is giving error in searchVoteByAge function in while loop :
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) in this line **
error :Exception in thread "main"
java.lang.NullPointerException at algorithms.Dijstra_algo.searchVoterByAge(Dijstra_algo.java:77) at
algorithms.Dijstra_algo.main(Dijstra_algo.java:55)
import java.util.Scanner;
public class Demo
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Voter voter[]=new Voter[4];
for(int i=0;i<voter.length;i++){
int v_id=sc.nextInt();
sc.nextLine();
String v_nme=sc.next();
sc.nextLine();
int v_age=sc.nextInt();
sc.nextLine();
boolean is_vote_casted=sc.nextBoolean();
sc.nextLine();
String constituency=sc.next();
sc.nextLine();
voter[i]=new Voter();
voter[i].setVoterId(v_id);
voter[i].setVoterName(v_nme);
voter[i].setVoterAge(v_age);
voter[i].setVoteCasted(is_vote_casted);
voter[i].setConstituency(constituency);
}
String cons=sc.next();
int c=findTotal(voter,cons);
if(c>0)
System.out.println(c);
else
System.out.println("No votes Casted");
Voter v[]=searchVoterByAge(voter);
if(v.length > 0){
for(Voter obj: v){
System.out.println(obj.getVoterId());
}
}
else
System.out.println("No such voters");
}
private static Voter[] searchVoterByAge(Voter[] voters) {
Voter v[]=new Voter[voters.length];
int k=0,f=0;
for(Voter obj:voters) {
if(obj.getVoterAge()<30) {
v[k]=new Voter();
v[k++]=obj;
f=1;
}
}
for(int i=1;i<v.length;i++) {
Voter key=v[i];
int j=i-1;
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) {
v[j+1]=v[j];
j--;
}
v[j+1]=key;
}
if(f == 0) {
return new Voter[0];
}
else
return v;
}
static int findTotal(Voter voters[],String s){
int c=0;
for(Voter voter:voters){
if(voter.isVoteCasted() && voter.getConstituency().equals(s)){
c++;
}
}
return c;
}
}
** Voter Class**
public class Voter {
private int voterId;
private String voterName;
private int voterAge;
private String constituency;
private boolean isVoteCasted;
public int getVoterId() {
return voterId;
}
public void setVoterId(int voterId) {
this.voterId = voterId;
}
public String getVoterName() {
return voterName;
}
public void setVoterName(String voterName) {
this.voterName = voterName;
}
public int getVoterAge() {
return voterAge;
}
public void setVoterAge(int voterAge) {
this.voterAge = voterAge;
}
public String getConstituency() {
return constituency;
}
public void setConstituency(String constituency) {
this.constituency = constituency;
}
public boolean isVoteCasted() {
return isVoteCasted;
}
public void setVoteCasted(boolean isVoteCasted) {
this.isVoteCasted = isVoteCasted;
}
}
I want to highlight the text in the TextView that matches the data taken from the database. I use the code below but the text in the TextView doesn't change color.
Here's my code, but the setters and getters looks useless.
class getICT {
#SerializedName("eng")
private String eng;
#SerializedName("bhs")
private String bhs;
#SerializedName("kor")
private String kor;
public getICT(String eng, String bhs, String kor, String imageURL){
this.eng = eng;
this.bhs = bhs;
this.kor = kor;
}
/*
GETTERS N SETTERS
*/
public String getEng() {
return eng;
}
public String getBhs() {
return bhs;
}
public String getKor() {
return kor;
}
#Override
public String toString() {
return eng;
}
}
This is my interface, get from database
interface MyAPIService {
#GET("/ICT03/danger.php")
Call<getICT[]> getICT();
}
I write the code for highlight the text from here
ShowDetected.MyAPIService myAPIService = ShowDetected.RetrofitClientInstance.getRetrofitInstance().create(ShowDetected.MyAPIService.class);
Call<getICT[]> call = myAPIService.getICT();
call.enqueue(new Callback<getICT[]>() {
#Override
public void onResponse(Call<getICT[]> call, Response<getICT[]> response) {
getICT[] icts = response.body();
String s = showInput.getText().toString();
for(int i = 0; i < icts.length; i++) {
if (icts[i].equals(s)) {
showInput.setText(s);
showInput.setTextColor(Color.RED);
} else {
showInput.setTextColor(Color.BLACK);
}
}
}
#Override
public void onFailure(Call<getICT[]> call, Throwable t) {
Toast.makeText(ShowDetected.this, ""+t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
Your code is incorrect, try this
boolean isHighlight = false
for(int i = 0; i < icts.length; i++) {
if (icts[i].equals(s)) {
isHighlight = true;
break;
}
}
showInput.setTextColor(isHighlight ? Color.RED : Color.BLACK);
I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState() {
if (varPass == 0) {
return isOff;
} else {
return isOn;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}
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());
}});
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.