I have been asked to implement a printDailyCost method which should call the getDailyCost method and format the value returned to two
decimal places. It should then print this value along with a £ sign.
So far I have:
public abstract class Suit {
private String colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
private double totalPrice;
public Suit(String colour, double dailyCost, int trouserLength,
int jacketChestSize, boolean available, double totalPrice) {
super();
this.colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
public String getColour() {
return colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean isAvailable() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setColour(String colour) {
this.colour = colour;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailable(boolean available) {
this.available = available;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public void calcTotalPrice(int numDaysHired){
this.totalPrice = dailyCost * numDaysHired;
}
public String printDailyCost() {
return printDailyCost();
}
}
My Question is how would I amend my printDailyCost method to call the getDailyCost method and format the value returned to two
decimal places then print with a £ sign?
Check this out:
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.UK);
System.out.println(format.format(getDailyCost()));
You can simply add them together and return it:
public String printDailyCost() {
return getDailyCost() + " £";
}
However I don't recommend to concatenate String with this way. Better use the following method using StringBuilder, that concatenates strings in the correct way:
public String printDailyCost() {
return (new StringBuilder().append(getDailyCost()).append(" £")).toString();
}
Or if you want to print it out to console, just do this:
System.out.println(getDailyCost() + " £");
Related
I need a little help, I'd already run out of ideas, tried to run this program out for two days, but I'm literally out of any ideas. So, I want from program to:
Display actual currency exchange
In another activity, the program should have a possibility to calculate currencies (let's say, we have a String with value "CZK" so the program should get from Model class currency value, to get that possibility to calculate the currencies, and here's the problem, I can't get those values. Actually, I can display it, but I want to call methods like getCZK(); because there are the actual values of those currencies. To be more accurate, ill try to explain it in other way: Let's say, the base currency is EUR, user selected option, that he want converse EUR to CZK, so program should have a String based of user choice (in this case it's String with value "CZK") now, program should search in switch case for value such as CZK, when it will find it, it should pass method like getCZK(); to suitable variable, to make conversion possible. I hope I explained it well to you guys.
Model class
public class Model {
#SerializedName("base")
private String base;
#SerializedName("rates")
private Map<String, Double> rates;
public void setRates(Map<String, Double> rates) {
this.rates = rates;
}
public void setBase(String base) {
this.base = base;
}
public String getBase() {
return base;
}
public Map<String, Double> getRates() {
return rates;
}
class Rates {
#SerializedName("BGN")
private Double bGN;
#SerializedName("NZD")
private Double nZD;
#SerializedName("ILS")
private Double iLS;
#SerializedName("RUB")
private Double rUB;
#SerializedName("CAD")
private Double cAD;
#SerializedName("USD")
private Double uSD;
#SerializedName("PHP")
private Double pHP;
#SerializedName("CHF")
private Double cHF;
#SerializedName("ZAR")
private Double zAR;
#SerializedName("AUD")
private Double aUD;
#SerializedName("JPY")
private Double jPY;
#SerializedName("TRY")
private Double tRY;
#SerializedName("HKD")
private Double hKD;
#SerializedName("MYR")
private Double mYR;
#SerializedName("THB")
private Double tHB;
#SerializedName("HRK")
private Double hRK;
#SerializedName("NOK")
private Double nOK;
#SerializedName("IDR")
private Double iDR;
#SerializedName("DKK")
private Double dKK;
#SerializedName("CZK")
private Double cZK;
#SerializedName("HUF")
private Double hUF;
#SerializedName("GBP")
private Double gBP;
#SerializedName("MXN")
private Double mXN;
#SerializedName("KRW")
private Double kRW;
#SerializedName("ISK")
private Double iSK;
#SerializedName("SGD")
private Double sGD;
#SerializedName("BRL")
private Double bRL;
#SerializedName("PLN")
private Double pLN;
#SerializedName("INR")
private Double iNR;
#SerializedName("RON")
private Double rON;
#SerializedName("CNY")
private Double cNY;
#SerializedName("SEK")
private Double sEK;
public Double getBGN() {
return bGN;
}
public void setBGN(Double value) {
this.bGN = value;
}
public Double getNZD() {
return nZD;
}
public void setNZD(Double value) {
this.nZD = value;
}
public Double getILS() {
return iLS;
}
public void setILS(Double value) {
this.iLS = value;
}
public Double getRUB() {
return rUB;
}
public void setRUB(Double value) {
this.rUB = value;
}
public Double getCAD() {
return cAD;
}
public void setCAD(Double value) {
this.cAD = value;
}
public Double getUSD() {
return uSD;
}
public void setUSD(Double value) {
this.uSD = value;
}
public Double getPHP() {
return pHP;
}
public void setPHP(Double value) {
this.pHP = value;
}
public Double getCHF() {
return cHF;
}
public void setCHF(Double value) {
this.cHF = value;
}
public Double getZAR() {
return zAR;
}
public void setZAR(Double value) {
this.zAR = value;
}
public Double getAUD() {
return aUD;
}
public void setAUD(Double value) {
this.aUD = value;
}
public Double getJPY() {
return jPY;
}
public void setJPY(Double value) {
this.jPY = value;
}
public Double getTRY() {
return tRY;
}
public void setTRY(Double value) {
this.tRY = value;
}
public Double getHKD() {
return hKD;
}
public void setHKD(Double value) {
this.hKD = value;
}
public Double getMYR() {
return mYR;
}
public void setMYR(Double value) {
this.mYR = value;
}
public Double getTHB() {
return tHB;
}
public void setTHB(Double value) {
this.tHB = value;
}
public Double getHRK() {
return hRK;
}
public void setHRK(Double value) {
this.hRK = value;
}
public Double getNOK() {
return nOK;
}
public void setNOK(Double value) {
this.nOK = value;
}
public Double getIDR() {
return iDR;
}
public void setIDR(Double value) {
this.iDR = value;
}
public Double getDKK() {
return dKK;
}
public void setDKK(Double value) {
this.dKK = value;
}
public Double getCZK() {
return cZK;
}
public void setCZK(Double value) {
this.cZK = value;
}
public Double getHUF() {
return hUF;
}
public void setHUF(Double value) {
this.hUF = value;
}
public Double getGBP() {
return gBP;
}
public void setGBP(Double value) {
this.gBP = value;
}
public Double getMXN() {
return mXN;
}
public void setMXN(Double value) {
this.mXN = value;
}
public Double getKRW() {
return kRW;
}
public void setKRW(Double value) {
this.kRW = value;
}
public Double getISK() {
return iSK;
}
public void setISK(Double value) {
this.iSK = value;
}
public Double getSGD() {
return sGD;
}
public void setSGD(Double value) {
this.sGD = value;
}
public Double getBRL() {
return bRL;
}
public void setBRL(Double value) {
this.bRL = value;
}
public Double getPLN() {
return pLN;
}
public void setPLN(Double value) {
this.pLN = value;
}
public Double getINR() {
return iNR;
}
public void setINR(Double value) {
this.iNR = value;
}
public Double getRON() {
return rON;
}
public void setRON(Double value) {
this.rON = value;
}
public Double getCNY() {
return cNY;
}
public void setCNY(Double value) {
this.cNY = value;
}
public Double getSEK() {
return sEK;
}
public void setSEK(Double value) {
this.sEK = value;
}
}
Api
public interface Api {
#GET("latest")
Call<Model> getRates();
#GET("latest")
Call<Model> getRatesByGivenCurrency(#Query("base") String base);
}
Java class
public class exchange_currency extends AppCompatActivity {
Api api;
TextView currentCurrency, fromTV, toTV, receivedValue;
EditText enteredValue;
Spinner spinner;
Button button;
List<Model> list;
String keyString;
double valueDouble;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exchange_currency);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.exchangeratesapi.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
spinner = (Spinner) findViewById(R.id.currencyNationalitiesSpinner);
button = (Button) findViewById(R.id.btn);
currentCurrency = (TextView) findViewById(R.id.currentValue);
fromTV = (TextView) findViewById(R.id.actualCurrency);
toTV = (TextView) findViewById(R.id.wantedCurrency);
receivedValue = (TextView) findViewById(R.id.receivedValue);
enteredValue = (EditText) findViewById(R.id.actualET);
api = retrofit.create(Api.class);
createRetrofit();
}
public void createRetrofit() {
Call<Model> call = api.getRates();
call.enqueue(new Callback<Model>() {
#Override
public void onResponse(Call<Model> call, Response<Model> response) {
if (!response.isSuccessful()) {
Toast.makeText(exchange_currency.this, response.code(), Toast.LENGTH_LONG).show();
}
list = Collections.singletonList(response.body());
for (Model model : list) {
Iterator<Map.Entry<String, Double>> entries = model.getRates().entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
keyString = (String) entry.getKey();
valueDouble = (Double) entry.getValue();
toTV.append(keyString + "\n");
receivedValue.append(String.valueOf(valueDouble) + "\n");
toTV.append((CharSequence) model.getRates());
}
}
}
#Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(exchange_currency.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Api that I using https://exchangeratesapi.io/
exemplary GET response from API
{"base":"EUR","rates":{"BGN":1.9558,"NZD":1.7056,"ILS":4.0147,"RUB":73.2104,"CAD":1.5117,"USD":1.1226,"PHP":58.898,"CHF":1.1307,"ZAR":15.9746,"AUD":1.6162,"JPY":123.0,"TRY":6.7732,"HKD":8.8112,"MYR":4.6818,"THB":35.362,"HRK":7.4113,"NOK":9.799,"IDR":16199.12,"DKK":7.4691,"CZK":25.751,"HUF":324.23,"GBP":0.86723,"MXN":21.5178,"KRW":1333.2,"ISK":137.8,"SGD":1.5366,"BRL":4.4743,"PLN":4.3061,"INR":79.0375,"RON":4.7615,"CNY":7.7252,"SEK":10.779},"date":"2019-05-14"}
these lines here
#SerializedName("rates")
private Map<String, Double> rates;
Should instead be like this
#SerializedName("rates")
private Rates rates;
Then in the onResponse you can get each of the values from the response like
Log.d("check", "CAD: "+response.body().getRates().getCAD());
Log.d("check", "GBP: "+response.body().getRates().getGBP());
Which returns
2019-05-14 17:27:16.015 6816-6816/com.test.testing D/check: CAD: 1.5117
2019-05-14 17:27:16.015 6816-6816/com.test.testing D/check: GBP: 0.86723
Does this answer your question?
I have been trying to make three different extended classes from a superclass. The problem is that only the first extended class works fine while the other two gets an error when I name them, and its says they should be in their own file. I have looked around to see if someone had a similar problem, but nothing exactly like this. The extended class that is working is the first one called "Smycken".
here is the code:
abstract public class Vardesaker
{
private String name;
double value;
public Vardesaker(String name, double value)
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
abstract public double getValue();
}
class Smycken extends Vardesaker
{
private int adelstenar;
private String material;
public Smycken(String name, double value, int adelstenar, String material)
{
super(name, 0);
this.adelstenar = adelstenar;
this.material = material;
}
public int getadelstenar()
{
return adelstenar;
}
public String getMaterial()
{
return material;
}
public double getValue()
{
if(material.equalsIgnoreCase("guld"))
{
double sum = 2000 + (500*adelstenar);
value = sum*1.25;
}
else
{
double sum = 700 + (500*adelstenar);
value = sum*1.25;
}
return value;
}
}
public class Aktier extends Vardesaker
{
private double kurs;
private int amount;
public Aktier (String name, double value, int amount, double kurs)
{
super(name, 0);
this.kurs = kurs;
this.amount = amount;
}
public double getKurs()
{
return kurs;
}
public int getAmount()
{
return amount;
}
public double getValue()
{
double sum = (int) (amount*kurs);
value = sum*1.25;
return value;
}
}
public class Apparater extends Vardesaker
{
private double price;
private int slitage;
public Apparater(String name, double value, double price, int slitage)
{
super(name, 0);
this.price = price;
this.slitage = slitage;
}
public double getPrice()
{
return price;
}
public int getSlitage()
{
return slitage;
}
public double getValue()
{
double sum = price*(slitage/10);
value = sum*1.25;
return value;
}
}
It is not because of extends, it is because of public keyword for the other classes. If you create multiple class with public keyword then they should be in their own compilation unit.
Check this answer for why each public class should have separate file.
There is a simple rule - 1 public type (class,interface,enum) = 1 java file
I am getting data from gemfire
List<String> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
which is like below:
[('price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996')]
This is a list of String I am getting.Currently I have 3 values in list.
I have a pojo class like below:
public class StockInfo {
// #Id
#JsonProperty("symbol")
private String symbol;
#JsonProperty("price")
private String price;
#JsonProperty("volume")
private String volume;
#JsonProperty("pe")
private String pe;
#JsonProperty("eps")
private String eps;
#JsonProperty("week53low")
private String week53low;
#JsonProperty("week53high")
private String week53high;
#JsonProperty("daylow")
private String daylow;
#JsonProperty("dayhigh")
private String dayhigh;
#JsonProperty("movingav50day")
private String movingav50day;
#JsonProperty("marketcap")
private String marketcap;
#JsonProperty("time")
private String time;
private String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPe() {
return pe;
}
public void setPe(String pe) {
this.pe = pe;
}
public String getEps() {
return eps;
}
public void setEps(String eps) {
this.eps = eps;
}
public String getWeek53low() {
return week53low;
}
public void setWeek53low(String week53low) {
this.week53low = week53low;
}
public String getWeek53high() {
return week53high;
}
public void setWeek53high(String week53high) {
this.week53high = week53high;
}
public String getDaylow() {
return daylow;
}
public void setDaylow(String daylow) {
this.daylow = daylow;
}
public String getDayhigh() {
return dayhigh;
}
public void setDayhigh(String dayhigh) {
this.dayhigh = dayhigh;
}
public String getMovingav50day() {
return movingav50day;
}
public void setMovingav50day(String movingav50day) {
this.movingav50day = movingav50day;
}
public String getMarketcap() {
return marketcap;
}
public void setMarketcap(String marketcap) {
this.marketcap = marketcap;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
How do I create a List of StockInfo class object from the value I am getting from restTemplate.getForObject
I think you could just use:
List<StockInfo> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
From my understanding this is what I am attempting to do,
I am creating an interface to outline what a character is,
I am creating a class to define each method that a Character will use.
In that same class I create a new object of that character as many times as I like.
So if I want to make 10 characters I just do that all from the same class?
Currently I am attempting to create one character by giving it attributes.
Then I want to System.out.prinln but when I compile I get
javac Hero.java
Hero.java:3: error: interface expected here
public class Hero implements Character {
^
1 error
I changed Character to Player and this is what I get,
javac Hero.java Hero.java:3: error: cannot find symbol public class Hero implements Player { ^ symbol: class Player 1 error
2 files Character Interface and Hero Class
public interface Character {
// define methods that must be defined across all character types
int getLevel();
String getPrimaryAttribute();
String getAttackType();
String getAbility1();
String getAbility2();
String getAbility3();
String getAbility4();
double getStrength();
double getStrengthMultiplier();
double getAgility();
double getAgilityMultiplier();
double getIntelligence();
double getIntelligenceMultiplier();
int getHealth();
int getMana();
int getDamageMin();
int getDamageMax();
int getRange();
double getArmor();
int getMovement();
}
public class Hero implements Character {
private int level;
private String primaryAttribute;
private String attackType;
private String ability1;
private String ability2;
private String ability3;
private String ability4;
private double strength;
private double strengthMultiplier;
private double agility;
private double agilityMultiplier;
private double intelligence;
private double intelligenceMultiplier;
private int health;
private int mana;
private int damageMin;
private int damageMax;
private int range;
private double armor;
private int movement;
//default constructor
public Hero(
int level,
String primaryAttribute,
String attackType,
String ability1,
String ability2,
String ability3,
String ability4,
double strength,
double strengthMultiplier,
double agility,
double agilityMultiplier,
double intelligence,
double intelligenceMultiplier,
int health,
int mana,
int damageMin,
int damageMax,
int range,
double armor,
int movement
) {
} // End Constructor
public static void main (String[] args) {
DrowRanger();
}
private static Object DrowRanger() {
Hero DrowRanger = new Hero(
0,
"Agility",
"Ranged",
"Frost Arrows",
"Gust",
"Precision Aura",
"Marksmanship",
17,
1.9,
26,
1.9,
15,
1.4,
473,
195,
44,
55,
625,
0.64,
300);
System.out.println(DrowRanger);
return DrowRanger();
}
// getters and setters - required to implement ALL from interface
public int getLevel() {
return this.level;
}
public String getPrimaryAttribute() {
return this.primaryAttribute;
}
public String getAttackType() {
return this.attackType;
}
public String getAbility1() {
return this.ability1;
}
public String getAbility2() {
return this.ability2;
}
public String getAbility3() {
return this.ability3;
}
public String getAbility4() {
return this.ability4;
}
public double getStrength() {
return this.strength;
}
public double getStrengthMultiplier() {
return this.strengthMultiplier;
}
public double getAgility() {
return this.agility;
}
public double getAgilityMultiplier() {
return this.agilityMultiplier;
}
public double getIntelligence() {
return this.intelligence;
}
public double getIntelligenceMultiplier() {
return this.intelligenceMultiplier;
}
public int getHealth() {
return this.health;
}
public int getMana() {
return this.mana;
}
public int getDamageMin() {
return this.damageMin;
}
public int getDamageMax() {
return this.damageMax;
}
public int getRange() {
return this.range;
}
public double getArmor() {
return this.armor;
}
public int getMovement() {
return this.movement;
}
// This is where the setters are.
public void setLevel(int level) {
this.level = level;
}
public void setPrimaryAttribute(String primaryAttribute) {
this.primaryAttribute = primaryAttribute;
}
public void setAttackType(String attackType) {
this.attackType = attackType;
}
public void setAbility1(String ability1) {
this.ability1 = ability1;
}
public void setAbility2(String ability2) {
this.ability2 = ability2;
}
public void setAbility3String(String ability3) {
this.ability3 = ability3;
}
public void setAbility4(String ability4) {
this.ability4 = ability4;
}
public void setStrength(double strength) {
this.strength = strength;
}
public void setStrengthMultiplier(double strengthMultiplier) {
this.strengthMultiplier = strengthMultiplier;
}
public void setAgility(double agility) {
this.agility = agility;
}
public void setAgilityMultiplier(double agilityMultiplier) {
this.agilityMultiplier = agilityMultiplier;
}
public void setIntelligence(double intelligence) {
this.intelligence = intelligence;
}
public void setIntelligenceMultiplier(double intelligenceMultiplier) {
this.intelligenceMultiplier = intelligenceMultiplier;
}
public void setHealth(int health) {
this.health = health;
}
public void setMana(int mana) {
this.mana = mana;
}
public void setDamageMin(int damageMin) {
this.damageMin = damageMin;
}
public void setDamageMax(int damageMax) {
this.damageMax = damageMax;
}
public void setRange(int range) {
this.range = range;
}
public void setArmor(double armor) {
this.armor = armor;
}
public void setMovement(int movement) {
this.movement = movement;
}
} // End Character Class
Java has a Character class defined already (in package java.lang).
The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.
EDIT - This package java.lang is imported by default and so the interface name clashes with the Character class defined in this package. Hence, the issue. It's always better to avoid using exactly same names anyway.
For example I have an incoming request with URL: "/cid/{cid}/{action}"
For path variable {action} I can have two values i.e. {action}: 1)list 2)tile
My POJO class with parameters for JSON output is below:
public class Area {
private Integer aId;
private String aName;
private Integer allSpaces;
private Integer violated;
private Integer percent;
private Integer level;
private List<Space> space = new ArrayList<Space>(); // this List should be depend on condition
public Area(Integer aId, String aName, Integer allSpaces, Integer violated, Integer percent, Integer level) {
this.aId = aId;
this.aName = aName;
this.allSpaces = allSpaces;
this.level = level;
this.violated = violated;
this.percent = percent;
}
public Integer getaId() {
return aId;
}
public void setaId(Integer aId) {
this.aId = aId;
}
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public Area addSpace(Space s) {
space.add(s);
return this;
}
public List<Space> getSpace() {
return space;
}
public void setSpace(List<Space> space) {
this.space = space;
}
public Integer getAllSpaces() {
return allSpaces;
}
public void setAllSpaces(Integer allSpaces) {
this.allSpaces = allSpaces;
}
public Integer getViolated() {
return violated;
}
public void setViolated(Integer violated) {
this.violated = violated;
}
public Integer getPercent() {
return percent;
}
public void setPercent(Integer percent) {
this.percent = percent;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
My output should not consist the parameter private List space = new ArrayList() for action =list but show it for action=tile.
It will of great help if any body can help me with this.
If the class gets serialized, and you want to exclude space from serialization to JSON, you can mark it as transient.
private transient List<Space> space = new ArrayList<Space>();
In the case where you would like to decide if this happens or not, you can subclass Area
So your controller would either invoke ListArea or TileArea.
I got the answer for my question
I intialized private List<Space> space = null; instead of private List<Space> space = new ArrayList<Space>();
and added #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) on top of my pojo like below
#JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Area {
now the parameters whose value==null will not be included in the serialized output, but I can intialize it dynamically by using constructur and retrive to output if required.