Setting variables in a class - java

I'm fairly new to Java and having a hard time understanding how to access the methodss and setting variables to a specific value that are in my Bean class. I am creating new instances of the Bean class and wanting to set the variables to a specific value. I also want to store these all in a List. Here is the code I have:
public class ReportBean
{
//instance variables
private String inventoryFulfillmentSpecialist;
private String inventoryFulfillmentManager;
private String poNumber;
private String poReferenceNumber;
private String shipToLoc;
private String poStatus;
private String importStatus;
private String orderType;
private String item;
private String mismatchFields;
private String tValue;
private String hValue;
/**
* Getter method for variable 'inventoryFulfillmentSpecialist'.
* #return String
*/
public String getInventoryFulfillmentManager() {
return inventoryFulfillmentManager;
}
/**
* Getter method for variable 'inventoryFulfillmentSpecialist'.
* #return String
*/
public String getInventoryFulfillmentSpecialist() {
return inventoryFulfillmentSpecialist;
}
/**
* Getter method for variable 'poNumber'.
* #return String
*/
public String getPoNumber() {
return poNumber;
}
/**
* Getter method for variable 'poReferenceNumber'.
* #return String
*/
public String getPoReferenceNumber() {
return poReferenceNumber;
}
/**
* Getter method for variable 'shipToLoc'.
* #return String
*/
public String getShipToLoc() {
return shipToLoc;
}
/**
* Getter method for variable 'poStatus'.
* #return String
*/
public String getPoStatus() {
return poStatus;
}
/**
* Getter method for variable 'importStatus'.
* #return String
*/
public String getImportStatus() {
return importStatus;
}
/**
* Getter method for variable 'orderType'.
* #return String
*/
public String getOrderType() {
return orderType;
}
/**
* Getter method for variable 'item'.
* #return String
*/
public String getItem() {
return item;
}
/**
* Getter method for variable 'tssVsPoMisMatchFields'.
* #return String
*/
public String getTssVsPODirectMisMatchFields() {
return tssVsPODirectMisMatchFields;
}
/**
* Getter method for variable 'tradeStoneValue'.
* #return String
*/
public String getTradeStoneValue() {
return tradeStoneValue;
}
/**
* Getter method for variable 'hostValue'.
* #return String
*/
public String getHostValue() {
return hostValue;
}
/**
* Setter method for variable 'inventoryFullfilmentManager'.
* #param inventoryFulfillmentManager String
*/
public void setInventoryFulfillmentManager(String inventoryFulfillmentManager) {
this.inventoryFulfillmentManager = inventoryFulfillmentManager;
}
/**
* Setter method for variable 'inventoryFulfillmentSpecialist'.
* #param inventoryFulfillmentSpecialist String
*/
public void setInventoryFulfillmentSpecialist(
String inventoryFulfillmentSpecialist) {
this.inventoryFulfillmentSpecialist = inventoryFulfillmentSpecialist;
}
/**
* Setter method for variable 'poNumber'.
* #param poNumber String
*/
public void setPoNumber(String poNumber) {
this.poNumber = poNumber;
}
/**
* Setter method for variable 'poReferenceNumber'.
* #param poReferenceNumber String
*/
public void setPoReferenceNumber(String poReferenceNumber) {
this.poReferenceNumber = poReferenceNumber;
}
/**
* Setter method for variable 'shipToLoc'.
* #param shipToLoc String
*/
public void setShipToLoc(String shipToLoc) {
this.shipToLoc = shipToLoc;
}
/**
* Setter method for variable 'poStatus'.
* #param poStatus String
*/
public void setPoStatus(String poStatus) {
this.poStatus = poStatus;
}
/**
* Setter method for variable 'importStatus'.
* #param importStatus String
*/
public void setImportStatus(String importStatus) {
this.importStatus = importStatus;
}
/**
* Setter method for variable 'orderType'.
* #param orderType String
*/
public void setOrderType(String orderType) {
this.orderType = orderType;
}
/**
* Setter method for variable 'item'.
* #param item String
*/
public void setItem(String item) {
this.item = item;
}
/**
* Setter method for variable 'tssVsPODirectMisMatchFields'.
* #param tssVsPODirectMisMatchFields String
*/
public void setTssVsPODirectMisMatchFields(String tssVsPODirectMisMatchFields) {
this.tssVsPODirectMisMatchFields = tssVsPODirectMisMatchFields;
}
/**
* Setter method for variable 'tradeStoneValue'.
* #param tradeStoneValue String
*/
public void setTradeStoneValue(String tradeStoneValue) {
this.tradeStoneValue = tradeStoneValue;
}
/**
* Setter method for variable 'hostValue'.
* #param hostValue String
*/
public void setHostValue(String hostValue) {
this.hostValue = hostValue;
}
List<ReportBean> reportData = new ArrayList<ReportBean>();
ReportBean bean1 = new ReportBean();
ReportBean bean2 = new ReportBean();
ReportBean bean3 = new ReportBean();
bean1.setInventoryFulfillmentManager("Jackie Luffman");
bean1.setInventoryFulfillmentSpecialist("Phillip Smith");
bean1.setPoNumber("348794798");
bean1.setPoReferenceNumber("140629700");
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("ReportBean: ");
sb.append("inventoryFulfillmentManager = " + getInventoryFulfillmentManager() + " ");
sb.append("inventoryFulfillmentSpecialist = " + getInventoryFulfillmentSpecialist() + " ");
sb.append("poNumber = " + getPoNumber() + " ");
sb.append("poReferenceNumber = " + getPoReferenceNumber() + " ");
sb.append("shipToLoc = " + getShipToLoc() + " ");
sb.append("poStatus = " + getPoStatus() + " ");
sb.append("importStatus = " + getImportStatus() + " ");
sb.append("orderType = + " + getOrderType() + " ");
sb.append("item = " + getItem() + " ");
sb.append("tssVsPODirectMisMatchFields = " + getTssVsPODirectMisMatchFields() + " ");
sb.append("tradeStoneValue = " + getTradeStoneValue() + " ");
sb.append("hostValue = " + getHostValue() + " ");
return sb.toString();
}
}
I get errors and when I try to say bean1.setxxxx I get the red squiggly line and it's says "syntax error on token(s), misplaced construct(s)". If anyone could help it would be much appreciated, thanks.

bean1.setInventoryFulfillmentManager("Jackie Luffman");
bean1.setInventoryFulfillmentSpecialist("Phillip Smith");
bean1.setPoNumber("348794798");
bean1.setPoReferenceNumber("140629700");
This part of the code is just floating inside your class. This is a structured programming thing. In Java, all the code must be inside a method or function.
you must use a static main method to encapsulate this:
public static void main(String[] args) {
//yourcode here
}

import java.util.ArrayList;
class ReportBean {
private String InventoryFulfillmentManager;
private String InventoryFulfillmentSpecialist;
private String PoNumber;
private String PoReferenceNumber;
// Default constructor
public ReportBean() {}
public void setInventoryFulfillmentManager(String value) {
this.InventoryFulfillmentManager = value;
}
public void setInventoryFulfillmentSpecialist(String value) {
this.InventoryFulfillmentSpecialist = value;
}
public void setPoNumber(String value) {
this.PoNumber = value;
}
public void setPoReferenceNumber(String value) {
this.PoReferenceNumber = value;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<ReportBean> list = new ArrayList<>();
for(int i = 0; i < 3; i++) {
list.add(new ReportBean());
list.get(i).setInventoryFulfillmentManager("Jackie Huffman");
list.get(i).setInventoryFulfillmentSpecialist("Phillip Smith");
list.get(i).setPoNumber("348794798");
list.get(i).setPoReferenceNumber("140629700");
}
}
}

Related

Gson.fromJson(json, Custom.class) empty string

i'm developing a small web application.
That's my problem:
This is executed when a user try to add a new record in my Datatable
#RequestMapping(value="/saveJokerRule", method= RequestMethod.POST, consumes= "application/json", produces = "application/json")
#ResponseBody
public String saveJokerRule(#RequestBody String json) {
System.out.println("JSON EDITOR:" + json.toString());
EditorResponse editorResponse = new EditorResponse();
JokerRuleForm jokerRuleForm = new GsonBuilder().serializeNulls().create().fromJson(json, JokerRuleForm.class);
...
}
This is the valid json received by the server and printed by a System call:
{"action":"create","data":{"0":{"jokerRule":{"group":1,"campaignPhase":"","dailyLimit":"","weeklyLimit":"","monthlyLimit":"","validFrom":"","activity":1}}}}
That's the JokerRuleForm classs
public class JokerRuleForm {
#Expose
String action;
#Expose
#SerializedName("data")
Map<String, JokerRuleView> data;
...
}
That's the JokerRuleView class
public class JokerRuleView {
String idJokerRule;
private AgentGroup group;
private JokerRule jokerRule;
private Activity activity;
public class JokerRule{
private String campaignPhase;
private Integer dailyLimit;
private Integer weeklyLimit;
private Integer monthlyLimit;
private Date validFrom;
private Date dateUpdate;
private String group;
private String activity;
/**
* #return the campaignPhase
*/
public String getCampaignPhase() {
return campaignPhase;
}
/**
* #param campaignPhase the campaignPhase to set
*/
public void setCampaignPhase(String campaignPhase) {
this.campaignPhase = campaignPhase;
}
/**
* #return the dailyLimit
*/
public Integer getDailyLimit() {
return dailyLimit;
}
/**
* #param dailyLimit the dailyLimit to set
*/
public void setDailyLimit(Integer dailyLimit) {
this.dailyLimit = dailyLimit;
}
/**
* #return the weeklyLimit
*/
public Integer getWeeklyLimit() {
return weeklyLimit;
}
/**
* #param weeklyLimit the weeklyLimit to set
*/
public void setWeeklyLimit(Integer weeklyLimit) {
this.weeklyLimit = weeklyLimit;
}
/**
* #return the monthlyLimit
*/
public Integer getMonthlyLimit() {
return monthlyLimit;
}
/**
* #param monthlyLimit the monthlyLimit to set
*/
public void setMonthlyLimit(Integer monthlyLimit) {
this.monthlyLimit = monthlyLimit;
}
/**
* #return the validFrom
*/
public Date getValidFrom() {
return validFrom;
}
/**
* #param validFrom the validFrom to set
*/
public void setValidFrom(Date validFrom) {
this.validFrom = validFrom;
}
/**
* #return the dateUpdate
*/
public Date getDateUpdate() {
return dateUpdate;
}
/**
* #param dateUpdate the dateUpdate to set
*/
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
/**
* #return the group
*/
public String getGroup() {
return group;
}
/**
* #param group the group to set
*/
public void setGroup(String group) {
this.group = group;
}
/**
* #return the activity
*/
public String getActivity() {
return activity;
}
/**
* #param activity the activity to set
*/
public void setActivity(String activity) {
this.activity = activity;
}
}
public class Activity {
String idActivity;
String name;
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the idGroup
*/
public String getIdActivity() {
return idActivity;
}
/**
* #param idGroup the idGroup to set
*/
public void setIdActivity(String idActivity) {
this.idActivity = idActivity;
}
}
public class AgentGroup {
String idGroup;
String name;
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the idGroup
*/
public String getIdGroup() {
return idGroup;
}
/**
* #param idGroup the idGroup to set
*/
public void setIdGroup(String idGroup) {
this.idGroup = idGroup;
}
}
/**
* #return the idJokerRule
*/
public String getIdJokerRule() {
return idJokerRule;
}
/**
* #param idJokerRule the idJokerRule to set
*/
public void setIdJokerRule(String idJokerRule) {
this.idJokerRule = idJokerRule;
}
/**
* #return the agentGroup
*/
public AgentGroup getGroup() {
return group;
}
/**
* #param agentGroup the agentGroup to set
*/
public void setGroup(AgentGroup group) {
this.group = group;
}
/**
* #return the jokerRule
*/
public JokerRule getJokerRule() {
return jokerRule;
}
/**
* #param jokerRule the jokerRule to set
*/
public void setJokerRule(JokerRule jokerRule) {
this.jokerRule = jokerRule;
}
/**
* #return the activity
*/
public Activity getActivity() {
return activity;
}
/**
* #param activity the activity to set
*/
public void setActivity(Activity activity) {
this.activity = activity;
}
}
JokerRuleForm jokerRuleForm = new GsonBuilder().serializeNulls().create().fromJson(json, JokerRuleForm.class);
When executing this line i got a NumberFormatException empty string and i think it dailyLimit's or date's fault because it's empty and fromJson() method can't do what he need to do.
I've read something about a TypeAdapter that seems can fit to my case, but i don't really know how to proceed and i'm not sure is a valid solution.
Can someone help me?
The limit fields e.g. dailyLimit are empty strings in your JSON. This was suggested in JsonParseException when encountering an empty value for an int or long #472 issue but Gson team closed it because it makes no sense to parse "" as int.
One of the users provided a solution in his comment which allows to leniently parse the number values. I'd not go this route myself and fix JSON instead, but it's up to you:
public static final TypeAdapter<Number> UNRELIABLE_INTEGER = new TypeAdapter<Number>() {
#Override
public Number read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
switch (jsonToken) {
case NUMBER:
case STRING:
String s = in.nextString();
try {
return Integer.parseInt(s);
} catch (NumberFormatException ignored) {
}
try {
return (int)Double.parseDouble(s);
} catch (NumberFormatException ignored) {
}
return null;
case NULL:
in.nextNull();
return null;
case BOOLEAN:
in.nextBoolean();
return null;
default:
throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
}
}
#Override
public void write(JsonWriter out, Number value) throws IOException {
out.value(value);
}
};
public static final TypeAdapterFactory UNRELIABLE_INTEGER_FACTORY = TypeAdapters.newFactory(int.class, Integer.class, UNRELIABLE_INTEGER);
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(UNRELIABLE_INTEGER_FACTORY)
.create();

Spring Form nested object Boolean field is not getting resolved

I have an Employee class which has PersonalDetails class object as a member
public class Employee {
private long empId;
private PersonalDetails personalDetails = new PersonalDetails();
// getters setters
PersonalDetails class is as follows
/**
* Class represents personal details of an employee
*
* <BR>
* <BR>
* <B>Supported API: </B>false <BR>
* <BR>
* <B>Extendable: </B>false
*/
public class PersonalDetails {
private String empfirstName, empMiddleName, empLastName, gender, birthPlace, marritalStatus,
longMedicalTreatmentDescription, suffix, ethnicity, veteranStatus, prefFirstName, preLastName, birthCountry,
citizenship, citizenshipCountry1, citizenshipCountry2, visaType, email;
private Address permanentAddress, presentAddress;
private OtherContactDetails emergencyContactDetails;
private Date dob, visaExp;
private int age, noOfChildrens, healthVision;
private Boolean hasPhysicalDisability, hadLongMedicalTreatment, hasFourWheelLiscence, isPresentAddressSame;
private Passport passportDetails;
private FatherOrHusband fatherOrHusbandDetails;
/**
* #return the empfirstName
*/
public String getEmpfirstName() {
return empfirstName;
}
/**
* #param empfirstName
* the empfirstName to set
*/
public void setEmpfirstName(String empfirstName) {
this.empfirstName = empfirstName;
}
/**
* #return the empMiddleName
*/
public String getEmpMiddleName() {
return empMiddleName;
}
/**
* #param empMiddleName
* the empMiddleName to set
*/
public void setEmpMiddleName(String empMiddleName) {
this.empMiddleName = empMiddleName;
}
/**
* #return the empLastName
*/
public String getEmpLastName() {
return empLastName;
}
/**
* #param empLastName
* the empLastName to set
*/
public void setEmpLastName(String empLastName) {
this.empLastName = empLastName;
}
/**
* #return the gender
*/
public String getGender() {
return gender;
}
/**
* #param gender
* the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* #return the birthPlace
*/
public String getBirthPlace() {
return birthPlace;
}
/**
* #param birthPlace
* the birthPlace to set
*/
public void setBirthPlace(String birthPlace) {
this.birthPlace = birthPlace;
}
/**
* #return the marritalStatus
*/
public String getMarritalStatus() {
return marritalStatus;
}
/**
* #param marritalStatus
* the marritalStatus to set
*/
public void setMarritalStatus(String marritalStatus) {
this.marritalStatus = marritalStatus;
}
/**
* #return the longMedicalTreatmentDescription
*/
public String getLongMedicalTreatmentDescription() {
return longMedicalTreatmentDescription;
}
/**
* #param longMedicalTreatmentDescription
* the longMedicalTreatmentDescription to set
*/
public void setLongMedicalTreatmentDescription(String longMedicalTreatmentDescription) {
this.longMedicalTreatmentDescription = longMedicalTreatmentDescription;
}
/**
* #return the permanentAddress
*/
public Address getPermanentAddress() {
return permanentAddress;
}
/**
* #param permanentAddress
* the permanentAddress to set
*/
public void setPermanentAddress(Address permanentAddress) {
this.permanentAddress = permanentAddress;
}
/**
* #return the presentAddress
*/
public Address getPresentAddress() {
return presentAddress;
}
/**
* #param presentAddress
* the presentAddress to set
*/
public void setPresentAddress(Address presentAddress) {
this.presentAddress = presentAddress;
}
/**
* #return the dob
*/
public Date getDob() {
return dob;
}
/**
* #param dob
* the dob to set
*/
public void setDob(Date dob) {
this.dob = dob;
}
/**
* #return the age
*/
public int getAge() {
return age;
}
/**
* #param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* #return the noOfChildrens
*/
public int getNoOfChildrens() {
return noOfChildrens;
}
/**
* #param noOfChildrens
* the noOfChildrens to set
*/
public void setNoOfChildrens(int noOfChildrens) {
this.noOfChildrens = noOfChildrens;
}
/**
* #return the healthVision
*/
public int getHealthVision() {
return healthVision;
}
/**
* #param healthVision
* the healthVision to set
*/
public void setHealthVision(int healthVision) {
this.healthVision = healthVision;
}
/**
* #return the passportDetails
*/
public Passport getPassportDetails() {
return passportDetails;
}
/**
* #param passportDetails
* the passportDetails to set
*/
public void setPassportDetails(Passport passportDetails) {
this.passportDetails = passportDetails;
}
/**
* #return the suffix
*/
public String getSuffix() {
return suffix;
}
/**
* #param suffix
* the suffix to set
*/
public void setSuffix(String suffix) {
this.suffix = suffix;
}
/**
* #return the fatherOrHusbandDetails
*/
public FatherOrHusband getFatherOrHusbandDetails() {
return fatherOrHusbandDetails;
}
/**
* #param fatherOrHusbandDetails
* the fatherOrHusbandDetails to set
*/
public void setFatherOrHusbandDetails(FatherOrHusband fatherOrHusbandDetails) {
this.fatherOrHusbandDetails = fatherOrHusbandDetails;
}
/**
* #return the hasPhysicalDisability
*/
public Boolean isHasPhysicalDisability() {
return hasPhysicalDisability;
}
/**
* #param hasPhysicalDisability
* the hasPhysicalDisability to set
*/
public void setHasPhysicalDisability(Boolean hasPhysicalDisability) {
this.hasPhysicalDisability = hasPhysicalDisability;
}
/**
* #return the hadLongMedicalTreatment
*/
public Boolean isHadLongMedicalTreatment() {
return hadLongMedicalTreatment;
}
/**
* #param hadLongMedicalTreatment
* the hadLongMedicalTreatment to set
*/
public void setHadLongMedicalTreatment(Boolean hadLongMedicalTreatment) {
this.hadLongMedicalTreatment = hadLongMedicalTreatment;
}
/**
* #return the hasFourWheelLiscence
*/
public Boolean isHasFourWheelLiscence() {
return hasFourWheelLiscence;
}
/**
* #param hasFourWheelLiscence
* the hasFourWheelLiscence to set
*/
public void setHasFourWheelLiscence(Boolean hasFourWheelLiscence) {
this.hasFourWheelLiscence = hasFourWheelLiscence;
}
/**
* #return the isPresentAddressSame
*/
public Boolean isPresentAddressSame() {
return isPresentAddressSame;
}
/**
* #param isPresentAddressSame
* the isPresentAddressSame to set
*/
public void setPresentAddressSame(Boolean isPresentAddressSame) {
if (isPresentAddressSame) {
presentAddress = permanentAddress;
}
this.isPresentAddressSame = isPresentAddressSame;
}
/**
* #return the ethnicity
*/
public String getEthnicity() {
return ethnicity;
}
/**
* #param ethnicity
* the ethnicity to set
*/
public void setEthnicity(String ethnicity) {
this.ethnicity = ethnicity;
}
/**
* #return the veteranStatus
*/
public String getVeteranStatus() {
return veteranStatus;
}
/**
* #param veteranStatus
* the veteranStatus to set
*/
public void setVeteranStatus(String veteranStatus) {
this.veteranStatus = veteranStatus;
}
/**
* #return the prefFirstName
*/
public String getPrefFirstName() {
return prefFirstName;
}
/**
* #param prefFirstName
* the prefFirstName to set
*/
public void setPrefFirstName(String prefFirstName) {
this.prefFirstName = prefFirstName;
}
/**
* #return the preLastName
*/
public String getPreLastName() {
return preLastName;
}
/**
* #param preLastName
* the preLastName to set
*/
public void setPreLastName(String preLastName) {
this.preLastName = preLastName;
}
/**
* #return the birthCountry
*/
public String getBirthCountry() {
return birthCountry;
}
/**
* #param birthCountry
* the birthCountry to set
*/
public void setBirthCountry(String birthCountry) {
this.birthCountry = birthCountry;
}
/**
* #return the citizenship
*/
public String getCitizenship() {
return citizenship;
}
/**
* #param citizenship
* the citizenship to set
*/
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
/**
* #return the citizenshipCountry1
*/
public String getCitizenshipCountry1() {
return citizenshipCountry1;
}
/**
* #param citizenshipCountry1
* the citizenshipCountry1 to set
*/
public void setCitizenshipCountry1(String citizenshipCountry1) {
this.citizenshipCountry1 = citizenshipCountry1;
}
/**
* #return the citizenshipCountry2
*/
public String getCitizenshipCountry2() {
return citizenshipCountry2;
}
/**
* #param citizenshipCountry2
* the citizenshipCountry2 to set
*/
public void setCitizenshipCountry2(String citizenshipCountry2) {
this.citizenshipCountry2 = citizenshipCountry2;
}
/**
* #return the visaType
*/
public String getVisaType() {
return visaType;
}
/**
* #param visaType
* the visaType to set
*/
public void setVisaType(String visaType) {
this.visaType = visaType;
}
/**
* #return the emergencyContactDetails
*/
public OtherContactDetails getEmergencyContactDetails() {
return emergencyContactDetails;
}
/**
* #param emergencyContactDetails
* the emergencyContactDetails to set
*/
public void setEmergencyContactDetails(OtherContactDetails emergencyContactDetails) {
this.emergencyContactDetails = emergencyContactDetails;
}
/**
* #return the visaExp
*/
public Date getVisaExp() {
return visaExp;
}
/**
* #param visaExp
* the visaExp to set
*/
public void setVisaExp(Date visaExp) {
this.visaExp = visaExp;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email
* the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "PersonalDetails [empfirstName=" + empfirstName + ", empMiddleName=" + empMiddleName + ", empLastName="
+ empLastName + ", gender=" + gender + ", birthPlace=" + birthPlace + ", marritalStatus="
+ marritalStatus + ", longMedicalTreatmentDescription=" + longMedicalTreatmentDescription + ", suffix="
+ suffix + ", ethnicity=" + ethnicity + ", veteranStatus=" + veteranStatus + ", prefFirstName="
+ prefFirstName + ", preLastName=" + preLastName + ", birthCountry=" + birthCountry + ", citizenship="
+ citizenship + ", citizenshipCountry1=" + citizenshipCountry1 + ", citizenshipCountry2="
+ citizenshipCountry2 + ", visaType=" + visaType + ", email=" + email + ", permanentAddress="
+ permanentAddress + ", presentAddress=" + presentAddress + ", emergencyContactDetails="
+ emergencyContactDetails + ", dob=" + dob + ", visaExp=" + visaExp + ", age=" + age
+ ", noOfChildrens=" + noOfChildrens + ", healthVision=" + healthVision + ", hasPhysicalDisability="
+ hasPhysicalDisability + ", hadLongMedicalTreatment=" + hadLongMedicalTreatment
+ ", hasFourWheelLiscence=" + hasFourWheelLiscence + ", isPresentAddressSame=" + isPresentAddressSame
+ ", passportDetails=" + passportDetails + ", fatherOrHusbandDetails=" + fatherOrHusbandDetails + "]";
}
}
I am using spring form tags to create registration form and added code as follows
<label>
<form:checkbox path="personalDetails.isPresentAddressSame" />
Present address same as above
</label>
As I have a variable personalDetails and it has a field isPresentAddressSame it should match the getter setter but I am getting following error
There was an unexpected error (type=Internal Server Error, status=500).
Invalid property 'personalDetails.isPresentAddressSame' of bean class [com.hr.foundation.models.doc.models.employee.Employee]: Bean property 'personalDetails.isPresentAddressSame' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Other fields with type String are matching with the path like personalDetails.firstName but not this Boolean field
You did not include the getter/setters of the PersonalDetails class, but Spring says that's where the error is.
Make sure you have these:
boolean isPresentAddressSame() { ... }
and
void setPresentAddressSame(boolean value) { ... }
Your mistake is likely that either:
You used a Boolean in either the parameter or return type (note the capital B)
You used getPresentAddressame which is only allowed for Boolean (note capital B again) instead of isPresentAddressSame which you should use for boolean (small B).
Clarification
Change:
public Boolean isPresentAddressSame() {
return isPresentAddressSame;
}
public void setPresentAddressSame(Boolean isPresentAddressSame) {
if (isPresentAddressSame) {
presentAddress = permanentAddress;
}
this.isPresentAddressSame = isPresentAddressSame;
}
to:
public boolean isPresentAddressSame() {
return isPresentAddressSame;
}
public void setPresentAddressSame(boolean isPresentAddressSame) {
if (isPresentAddressSame) {
presentAddress = permanentAddress;
}
this.isPresentAddressSame = isPresentAddressSame;
}
Note again that the boolean here uses a small b.
Try to change the signature of the method:
public Boolean isPresentAddressSame() {
return isPresentAddressSame;
}
to
public Boolean getPresentAddressSame() {
return isPresentAddressSame;
}
if you are using spring, spring alwais looking for get word to resolve the beans properties.

Creating an array with 3 variables

I am trying to create an array of students which will contain 3 different types of students and each of the students will have 3 variables name, and 2 grades.
This is what I have done so far, and it gives me the following error cannot find symbol.
Main class:
public class JavaLab5 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(Smith,14,15);
s[1] = new MathStudent(Jack,16,19);
s[2] = new MathStudent(Victor,18,21);
s[3] = new MathStudent(Mike,23,28);
s[4] = new ScienceStudent(Dave,32,25);
s[5] = new ScienceStudent(Oscar,28,56);
s[6] = new ScienceStudent(Peter,29,28);
s[7] = new ComputerStudent(Philip,25,38);
s[8] = new ComputerStudent(Shaun,34,39);
s[9] = new ComputerStudent(Scott,45,56);
for (int loop = 0; loop < 10; loop++) {
System.out.println(s[loop].getSubjects());
System.out.print(loop + " >>" + s[loop]);
}
}
}
This is the Student class:
public class Student {
private String name;
//private int age;
//public String gender = "na";
public static int instances = 0;
// Getters
//public int getAge() {
//return this.age;
//}
public String getName() {
return this.name;
}
// Setters
//public void setAge(int age) {
//this.age = age;
//}
public void setName(String name) {
if (JavaLab5.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age and gender
* with defaults
*/
public Student() {
instances++;
//this.age = 18;
this.name = "Not Set";
//this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(String name) {
//this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
//public Student(String gender) {
//this(); // Must be the first line!
//this.gender = gender;
//}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable {
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString () {
return "Name: " + this.name; //+ " Age: " + this.age + " Gender: "
//+ this.gender;
}
public String getSubjects() {
return this.getSubjects();
}
}
and this is the MathStudent class which inherits from the Student class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
/**
* Default constructor
* #param name
* #param algebraGrade
* #param calculusGrade
*/
public MathStudent(String name, float algebraGrade, float calculusGrade) {
super();
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return(" Math Student >> " + "Algebra Grade: " + algebraGrade
+ " Calculus Grade: " + calculusGrade);
}
}
Check how you instantiate students, i.e.
new MathStudent(Smith,14,15);
The name should be in quotes like "Smith"
new MathStudent("Smith",14,15);
Otherwise Smith will be interpreted as variable and this one is not defined.

How do you create an access method to convert a string to a boolean

How do you create an access method to convert a string to a boolean?
current access method below
protected boolean fullTime;
/**
* Get the value of fullTime
*
* #return the value of fullTime
*/
public boolean isFullTime() {
return fullTime;
}
/**
* Set the value of fullTime
*
* #param fullTime new value of fullTime
*/
public void setFullTime(boolean fullTime) {
this.fullTime = fullTime;
}
Can it be done similar to this below
/**
* set the coaches names
* #param coaches as an array of strings
*/
public void setCoaches(String coaches)
{
this.coaches = getStringAsArray(coaches);
}
public String getCoachesAsString()
{
return getArrayAsString(coaches);
}
Like this?
protected boolean fullTime;
public String getFullTimeAsString(){
return Boolean.toString(fullTime);
}
public void setFullTimeAsString(String fulltimeStr){
fullTime = "true".equalsIgnoreCase(fulltimeStr);
}
EDITED:
private static final String YES = "yes";
private static final String NO = "no";
protected boolean fullTime;
public String isFullTimeAsString() {
return fullTime? YES: NO;
}
public void setFullTime(String fullTime) {
this.fullTime =YES.equalsIgnoreCase(fullTime);
}
Is this what you wanted?
protected boolean fullTime;
public String isFullTimeAsString() {
return String.valueOf(fullTime);
}
public void setFullTime(String fullTime) {
this.fullTime = Boolean.parseBoolean(fullTime);
}

I am getting the memory address from an arraylist, need info

I am taking a text file and filling an arraylist. To test the file I am printing it out before I move on. I am only able to see the memory address and not the actual info from the file. Is there something simple and probably obvious I'm missing?
public class TriviaQuestion {
private String player;
private String category;
private String question;
private String answer;
private int score = 0;
/**
*
*/
public TriviaQuestion() {
player = "unknown";
category = "unknown";
question = "unknown";
answer = "unknown";
score = 0;
}
public TriviaQuestion(String category, String question, String answer){
}
public TriviaQuestion(String player, String category, String question,
String answer, int score) {
super();
this.player = player;
this.category = category;
this.question = question;
this.answer = answer;
this.score = score;
}
/**
* #return the player
*/
public String getPlayer() {
return player;
}
/**
* #param player the player to set
*/
public void setPlayer(String player) {
this.player = player;
}
/**
* #return the category
*/
public String getCategory() {
return category;
}
/**
* #param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* #return the question
*/
public String getQuestion() {
return question;
}
/**
* #param question the question to set
*/
public void setQuestion(String question) {
this.question = question;
}
/**
* #return the answer
*/
public String getAnswer() {
return answer;
}
/**
* #param answer the answer to set
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/**
* #return the score
*/
public int getScore() {
return score;
}
/**
* #param score the score to set
*/
public void setScore(int score) {
this.score = score;
}
}
The tester
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class TriviaQuestionTester {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
File triviaFile = new File("trivia.txt");
Scanner triviaFile1 = new Scanner(triviaFile);
String lastKnownCategory = "";
ArrayList<TriviaQuestion> myList = new ArrayList<TriviaQuestion>();
while (triviaFile1.hasNextLine()){
String currentLine = triviaFile1.nextLine();
if (!currentLine.isEmpty()) {
TriviaQuestion currentQuestion = new TriviaQuestion(currentLine, currentLine, currentLine);
if (currentLine.endsWith("?")) {
currentQuestion.setCategory(lastKnownCategory);
currentQuestion.setQuestion(currentLine);
currentQuestion.setAnswer(triviaFile1.nextLine());
} else {
currentQuestion.setCategory(currentLine);
currentQuestion.setQuestion(triviaFile1.nextLine());
currentQuestion.setAnswer(triviaFile1.nextLine());
lastKnownCategory = currentLine;
}
myList.add(currentQuestion);
}
}
triviaFile1.close();
System.out.println(myList);
}
}
Is there something simple and probably obvious I'm missing?
Yes - you haven't overridden toString in TriviaQuestion, so you're getting the default implementation from Object:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Just add this to TriviaQuestion:
#Override public String toString() {
return "Player: " + player + "; Category: " + category
+ "; Question: " + question + "; Answer: " + answer
+ "; Score: " + score;
}
(Or use String.format within the method to do the same kind of thing.)
You need to override the toString method in your TriviaQuestion class to print the objects in the way you want to. The defualt implementation of toString method prints the memory representation of object.
Note: If you don't know how to write toString method, then make use of some IDE such as eclipse to generate the toString method for you. In eclipse,
go to your class in the editor, right click-> source - > generate
toString.

Categories