How to store data from a method after calling it? - java

I'm trying to store the data in a variable in the CongressStats that I fetched from the printPartyBreakdownInSenate method without "capturing" it and returning the value somehow.
public class CongressStats
{
private int congressNum;
public void printPartyBreakdownInSenate() {
CongressDataFetcher.fetchSenateData(congressNum);
}
here is the method I calling from.
public static String fetchSenateData(int congressNum)
{
return fetchCongressData(Chamber.SENATE, congressNum);
}

The method has a return type for String objects, so you could try something like so:
int yourValueHere = 0;
String store = fetchSenateData(yourValueHere);

This is "return" statement so it is last statement in your method and when method is gone all internal variables are gone too. You can "store" value somewhere outside of the method. For example in class variables. something like this:
class Test {
String storedValue;
public static String fetchSenateData(int congressNum)
{
return storedValue=fetchCongressData(Chamber.SENATE, congressNum);//<--Store this
}
}
This is possible because result of assigning operator "=" is the value assigned in this operator.

private static Map<Integer, String> map = new HashMap<Integer, String>();
public static String fetchSenateData(int congressNum) {
Integer i = new Integer(congressNum);
if (map.containsKey(i) {
return map.get(i);
} else {
String s = fetchCongressData(Chamber.SENATE, congressNum);
map.put(i, s);
return s;
}
}

Related

How to use variable of method from 1 class in 2 class via Java?

public static class One {
#Override
public String interact(String... values) {
String actualTextOne = "test";
return actualTextOne;
}
}
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
/* Here I need to compare actualTextOne and actualTextTwo, but the problem is that I can't find solluction how to use actualTextOne in Two class*/
return actualTextTwo;
}
}
You cannot do that.
Please check variable scope in java.
https://www.codecademy.com/articles/variable-scope-in-java
A possible solution here is to call the method interact from the class One. Something like this
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
One one = new One();
String actualTextOne = one.interact(values);
// compare values here
return actualTextTwo;
}
}
Why in your classes functions have parameters if you dont use it?
You can mark your class with static only if he is nested, else you need do like this:
class Two {
static public String interact(String... values) {
String actualTextTwo = "test";
return actualTextTwo;
}
}
String textOne = One.interact("");
String textTwo = Two.interact("");
System.out.println(textOne==textTwo);

How to parse values from a hashmap to a variable

So I'm trying to create a class which only stores a hashmap and it's values as I will need to access them from another class at some point and it's values could change at any point. Below is an example of what I'm trying
PriceInfo.java
public class PriceInfo {
public static HashMap PriceInformation() {
HashMap<String, Double> trainerPrice = new HashMap<>();
trainerPrice.put("Nike", 199.99);
trainerPrice.put("Adidas", 150.99);
return trainerPrice;
}
}
DiscountChecker.java
public class DiscountChecker {
public boolean AllowDiscount(String discountCode, String tBrand) {
if (discountCode.equals("Hello")) {
double tPrice = PriceInfo.PriceInformation().get(tBrand);
double discountedPrice = 0.8 * tPrice;
return true;
} else {
return false;
}
}
}
At the moment, I keep getting an error saying incompatible types and double is required.
The error is on this line double tPrice = PriceInfo.PriceInformation().get(tBrand);
Change the signature of your method from
public static double PriceInformation ()
to
public static Map<String, Double> PriceInformation ()
Aside: Please follow proper naming conventions and change your method names to start with lowercase.

Sorting ArrayList Hashmap

I have an ArrayList<HashMap<String,String>> and I want to sort it. My ArrayList output in Logcat is like this:
[{num=0, username=p, startPoliPro=A, finalPoliPro=B, diff=0},
{num=1, username=e, startPoliPro=C, finalPoliPro=D, diff=548.0Km},
{num=2, username=e, startPoliPro=E, finalPoliPro=F, diff=3.0Km}]
I want to sort the list based on "diff" value by ascending order so that Logcat has to be like:
[{num=0, username=p, startPoliPro=A, finalPoliPro=B, diff=0},
{num=2, username=e, startPoliPro=E, finalPoliPro=F, diff=3.0Km},
{num=1, username=e, startPoliPro=C, finalPoliPro=D, diff=548.0Km}]
I have read many similar topics and tried something like
Collections.sort(final_itinList, new Comparator<HashMap< String,String >>() {
#Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
// Do your comparison logic here and retrn accordingly.
return lhs.get("diff").compareTo(rhs.get("diff"));
}
});
with no success. Any help would be appreciated
Currently, you are trying to compare two String Objects:
return lhs.get("diff").compareTo(rhs.get("diff"));
What you really want to do is comparing the returned Integers, so you would need to do something like this:
return (Integer.parseInt(lhs.get("diff")) - Integer.parseInt(rhs.get("diff")));
Your Comparator is comparing two Strings. That's probably why the list is not sorted correctly. The "diff" string should be parsed as an integer (or float) to compare it.
If your objects always have the same structure, I would advise to create a List of a custom object (where the diff is an integer representing the number of kilometers) instead of using a List of Maps. In that case, you could make your custom object implement Comparable.
Something like :
public class MyCustomObject implements Comparable<MyCustomObject> {
private String mNum;
private String mUsername;
private String mStartPoliPro;
private String mFinalPoliPro;
private int mDiff;
#Override
public int compareTo(MyCustomObject another) {
return mDiff - another.getDiff();
}
public String getNum() {
return mNum;
}
public void setNum(String num) {
mNum = num;
}
public String getUsername() {
return mUsername;
}
public void setUsername(String username) {
mUsername = username;
}
public String getStartPoliPro() {
return mStartPoliPro;
}
public void setStartPoliPro(String startPoliPro) {
mStartPoliPro = startPoliPro;
}
public String getFinalPoliPro() {
return mFinalPoliPro;
}
public void setFinalPoliPro(String finalPoliPro) {
mFinalPoliPro = finalPoliPro;
}
public int getDiff() {
return mDiff;
}
public void setDiff(int diff) {
mDiff = diff;
}
}
and then simply call
List<MyCustomObject> myList = // create your object list
Collections.sort(myList);

How do i display an objects integer value in a text view from another class?

I have a String in a class that is separate from another class and in this string i want to get an integer from an object of the other class, this object is in a class of its own.
Class with string below
TextView2.setText(//I want the objects integer value displayed here);
Class with object below
testClass Object = new testClass();
Object.setIntegerValue(5);
Class of which object was created from below
int integerValue;
public int getIntegerValue()
{
return integerValue;
}
public void setIntegerValue(int i)
{
IntegerValue = i;
}
How do i display "Object"'s integer value in the TextView 2 without the app crashing?
TextView.setText(object.getIntegerValue().toString());
Use TextView2.setText(Integer.toString(Object.getIntegerValue()));.
If you use just TextView2.setText(Object.getIntegerValue()), the TextView will try to find a String in Resource which id is the value of Object.getIntegerValue().
Just use the getter from the testClass:
TextView2.setText(Integer.toString(Object.getIntegerValue()));
public int getIntegerValue()
{
return integerValue;
}
public void setIntegerValue(int i)
{
IntegerValue = i;
}
I see an error here, when you call the setIntegervalue() function, you're modifying the value of IntegerValue variable, but you return the value of integerValue(which is different from IntegerValue) when calling the getIntegerValue() funvtion . Java is case-sensitive, so you're modifying and returning a different variable each time. See if this is not you're problem.
This should do it.
public int getIntegerValue()
{
return this.integerValue;
}
public void setIntegerValue(int i)
{
this.integerValue = i;
}
and for your TextView
textView.setText(object.getIntegerValue() + "");

return multiple value from one method

I have a class UserFunction and it have two method getAudioFunction and getPromptFunction with returning String value, my problem is that i want to return both value in one method
how can i able to do that
UserFunction.java
public class UserFunction{
Map<String,PromptBean> promptObject=new HashMap<String,PromptBean>();
Map<String,AudioBean> audioObject = new HashMap<String,AudioBean>();
XmlReaderPrompt xrpObject=new XmlReaderPrompt();
public String getAudioFunction(String audioTag,String langMode )
{
Map<String, AudioBean> audioObject=xrpObject.load_audio(langMode);
AudioBean audioBean=(AudioBean)audioObject.get(audioTag);
String av=StringEscapeUtils.escapeXml(audioBean.getAudio());
return av;
}
public String getPromptFunction(String promptTag,String langMode )
{
Map<String, PromptBean> promptObject=xrpObject.load(langMode);
PromptBean promptBean= (PromptBean)promptObject.get(promptTag);
String pv=StringEscapeUtils.escapeXml(promptBean.getPrompt());
return pv;
}
}
You need to return an object which holds both values. You could create a class for this purpose. The class can have two getter methods for retrieving the values.
It is not possible to return more than one value from a method in java. You can set multiple value into Map or List or create a custom class and can return that object.
public Map<String,String> getAudioAndPromptFunction(String audioTag,String langMode )
{
Map<String,String> map =new HashMap();
...
map.put("audioBean",StringEscapeUtils.escapeXml(audioBean.getAudio()));
map.put("promptBean",StringEscapeUtils.escapeXml(promptBean.getPrompt());
return map;
}
or you can create a custom bean class like.
public class AudioPrompt{
private String audioBean;
private String promptBean;
...
}
public AudioPrompt getAudioAndPromptFunction(String audioTag,String langMode )
{
AudioPrompt audioPrompt =new AudioPrompt();
...
audioPrompt.set(StringEscapeUtils.escapeXml(audioBean.getAudio()));
audioPrompt.set(StringEscapeUtils.escapeXml(promptBean.getPrompt());
return audioPrompt ;
}
You'll need to return an object that includes both of the values. This could be an array with two elements, a Pair<A,B> class (which holds two generic values, typically from some pan-project utility library), or a method-specific class such as:
public class UserFunctionXmlPairing {
public final String audioBeanXml;
public final String promptBeanXml;
}
Create a new class that holds your two strings and return that.
class AudioPromptPair {
private String audio;
private String prompt;
public AudioPromptPair(String audio, String prompt) {
this.audio = audio;
this.prompt = prompt;
}
// add getters and setters
}
You can wrap all the values you wish into a single object and return that:
public class Prompts {
private Map<String, Object> prompts = new HashMap<String, Object>();
public void addPrompt(String name, Object prompt) {
this.prompts.put(name, prompt);
}
public Object getPrompt(String name) {
this.prompts.get(name);
}
}
It's even easier if your AudioBean and PromptBean have a common super class or interface.
My preference would be to lose the "Bean" in your class names. AudioPrompt and TextPrompt would be preferred.

Categories

Resources