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.
Related
I have created a class like this, which contains a bunch of arraylist as you can see. I've been setting the array with the methods add.. and then retrieving it with get.., when i tried to System.out.println numberofcitizen for example it is returning 0. Note that i have instantiated the class in another class to set the values.
public int numberOfCitizen;
private final ArrayList<Integer> citizenid = new ArrayList<>();
private final ArrayList<String> citizenName = new ArrayList<>();
private final ArrayList<Integer> citizenWaste = new ArrayList<>();
private final ArrayList<Float> longitude = new ArrayList<>();
private final ArrayList<Float> latitude = new ArrayList<>();
private final ArrayList<String> address = new ArrayList<>();
public void working() {
System.out.println("executing fine");
}
public void setnoOfcit(int number) {
this.numberOfCitizen = number;
}
public int getnumber() {
return this.numberOfCitizen;
}
public void addCitizenId(int citizen) {
citizenid.add(citizen);
}
public int getCitizenid(int i) {
int citId = citizenid.get(i);
return citId;
}
public void addCitizenName(String citizenname) {
citizenName.add(citizenname);
}
public String getCitizenName(int i) {
return citizenName.get(i);
}
public void addCitizenWaste(int waste) {
citizenWaste.add(waste);
}
public int getCitizenWaste(int i) {
return citizenWaste.get(i);
}
public void addLatitude(float lat) {
latitude.add(lat);
}
public float getLat(int i) {
return latitude.get(i);
}
public void addlng(float lng) {
longitude.add(lng);
}
public float getlng(int i) {
return longitude.get(i);
}
com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder vrpBuilder = com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder.newInstance();
public void runVPRSolver() {
System.out.println(numberOfCitizen);
System.out.println(getCitizenName(0));
//create a loop to fill parameters
Probable source of problem :
numberOfCitizen is a member attribute that you seem to never change. If you want it to represent the number of elements in your lists, either use citizenName.size() or increment the value of numberOfCitizen in one of the add methods.
Design flaw :
Your design takes for granted that your other class always use that one properly. Anytime you or someone uses that class, he must make sure that he add every single element manually. This adds code that could be grouped inside your class, which would be cleaner and easier to maintain.
So instead of several add method like this :
addCitizenid();
addCitizenName();
addCitizenWaste();
addLongitude();
addLatitude();
addAddress();
Design an other Citizen class which will contain those elements, and use a single list of instances of that class. That way you can use only one method :
private List<Citizen> citizenList = new ArrayList<>();
public void addCitizen(Citizen c) {
/*Add element in your list*/
citizenList.add(c);
}
This programming methodology is called "Encapsulation" which you can read about here
You need to increment numberOfCitizen in your add methods. For example:
public void addCitizenId(int citizen){
citizenid.add(citizen);
numberOfCitizen++;
}
I would also suggest encapsulating your variables into Objects, so create a citizen class:
public class Citizen {
private Integer id;
private Integer name;
private Integer waste;
}
And change your variable to an ArrayList of objects:
ArrayList<Citizen> citizens;
The thing is, I have an ExpandableListView with 2 groups, inside of each group I have some users and when I click on these users I get their ids and add to a HashMap of strings, now I'm trying to remove these ids when I click on them for the second time, but the ids of the second group are not being deleted. here is what I'm trying to do:
aMap = new HashMap < String, GPSEscolas > ();
TextView idAluno = (TextView) v.findViewById(R.id.idcrianca);
TextView idEscola = (TextView) v.findViewById(R.id.idescola);
IdEscola = String.valueOf(idEscola.getText());
IdAluno = String.valueOf(idAluno.getText());
mGpsEscolas = aMap.get(IdEscola);
if (mGpsEscolas == null) {
mGpsEscolas = new GPSEscolas();
aMap.put(IdEscola, mGpsEscolas);
mGpsEscolas.getIds_alunos().add(String.valueOf(IdAluno));
mGpsEscolas.setAlunos(IdAluno);
} else {
Set < String > ia = mGpsEscolas.getIds_alunos();
if (!ia.contains(IdAluno)) {
ia.add(String.valueOf(IdAluno));
} else {
alunos = aMap.get(IdEscola).getAlunos();
ia.remove(IdAluno);
aMap.remove(alunos);
}
stringArray = new String[ia.size()];
out = "";
if (ia.size() > 0) {
for (String str: ia.toArray(stringArray)) {
out += ";" + str;
}
aMap.get(IdEscola).setAlunos(out.substring(1));
}
}
MOdel:
public class GPSEscolas implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id_escola;
private Set<String> ids_alunos = new TreeSet<String>();
private String Alunos;
private double distancia;
private Float latitude;
private Float longitude;
public String getAlunos() {
return Alunos;
}
public void setAlunos(String alunos) {
Alunos = alunos;
}
public Integer getId_escola() {
return id_escola;
}
public void setId_escola(Integer id_escola) {
this.id_escola = id_escola;
}
public Set<String> getIds_alunos() {
return ids_alunos;
}
public void setIds_alunos(Set<String> ids_alunos) {
this.ids_alunos = ids_alunos;
}
public double getDistancia() {
return distancia;
}
public void setDistancia(double distancia) {
this.distancia = distancia;
}
public Float getLatitude() {
return latitude;
}
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
public Float getLongitude() {
return longitude;
}
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
}
I assume you are referring to this line:
aMap.remove(alunos);
... which is the only place where you are trying to remove from a HashMap.
If that's the case, the problem is that you are not passing the right parameter value to aMap.remove(). That method expects you to pass a key value, such as whatever IdEscola is, which is the key value you used to do a put in the HashMap.
But instead, you are passing in alunos, which I can't quite be sure what that is, but it looks like a list of students.
So I think that what you wanted to do was to simply do aMap.remove(IdEscola).
EDIT: I now realize that your hashmap is keyed by school, so I changed my answer.
EDIT 2: And if the above is not what you want, then you probably don't want to remove anything from that HashMap.
If your key objects are different while putting(aMap.put(IdEscola, mGpsEscolas)) and getting (aMap.get(IdEscola).getAlunos()) are two different objects then hashmap will return null even when they are logically same values.
Read about object class in java and it's equals() and hashcode() functions , hashmap class uses it.
Student A= new Student ("ram");
Student B= new Student ("ram");
map.put(A,"10");
map.get(B) will return null.
If you use object A as a key to put some element in map then you cant use object B to retrieve it , even when they are logically same .
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;
}
}
I have a bunch of error codes being returned to me by the server. Based on these error codes I need to write some logic for each error code. I don't want to place the plain error in my function. What is the best way to represent these error codes?
I am using an enum for now,
private enum LoginErrorCode{
EMAIL_OR_PASSWORD_INCORRECT("101"),
EMAIL_INCORRECT("102");
private final String code;
LoginErrorCode(String code){
this.code=code;
}
public String getCode(){
return code;
}
}
But I do not know how to handle it if I get an error code unknown to me. Please let me know.
Here is the solution using your Enum that I typically employ to deal with error codes as you have explained in your scenario:
import java.util.HashMap;
import java.util.Map;
public class EnumSample {
public static enum LoginErrorCode {
EMAIL_OR_PASSWORD_INCORRECT("101"), EMAIL_INCORRECT("102"), UNKNOWN_ERROR_CODE("---");
private static Map<String, LoginErrorCode> codeToEnumMap;
private final String code;
LoginErrorCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
/**
* Looks up enum based on code. If code was not registered as enum, it returns UNKNOWN_ERROR_CODE
* #param code
* #return
*/
public static LoginErrorCode fromCode(String code) {
// Keep a hashmap of mapping between code and corresponding enum as a cache. We need to initialize it only once
if (codeToEnumMap == null) {
codeToEnumMap = new HashMap<String, EnumSample.LoginErrorCode>();
for (LoginErrorCode aEnum : LoginErrorCode.values()) {
codeToEnumMap.put(aEnum.getCode(), aEnum);
}
}
LoginErrorCode enumForGivenCode = codeToEnumMap.get(code);
if (enumForGivenCode == null) {
enumForGivenCode = UNKNOWN_ERROR_CODE;
}
return enumForGivenCode;
}
}
public static void main(String[] args) {
System.out.println( LoginErrorCode.fromCode("101")); //Prints EMAIL_OR_PASSWORD_INCORRECT
System.out.println( LoginErrorCode.fromCode("102")); //Prints EMAIL_INCORRECT
System.out.println( LoginErrorCode.fromCode("999")); //Prints UNKWNOWN_ERROR_CODE
}
}
The point of an enum is that there are no invalid values; invalid values do not exist. There can't be an LoginErrorCode.EMAIL_ERROR_DOES_NOT_EXIST value. You shouldn't have to deal with a non-existent value. That is what makes an enum the best representation, because you have a known set of values to represent.
EDIT
Since you need to translate the error code strings to your enum, include a Map of the error code Strings to your enum values:
public enum LoginErrorCode
{
EMAIL_OR_PASSWORD_INCORRECT,
EMAIL_INCORRECT;
private static Map<String, LoginErrorCode> map;
// static initializer
static {
map = new HashMap<String, LoginErrorCode>();
map.put("101", EMAIL_OR_PASSWORD_INCORRECT);
map.put("102", EMAIL_INCORRECT);
}
public static LoginErrorCode fromCode(String code)
{
return map.get(code);
}
}
The fromCode method will return null on an invalid code.
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.