I can get my data, because i get an error on line 66 which is. but error saying that I get a null value. although I've looked through the code, I think even that, it gets the right value in. I tried using a method that I made just for it. but after that it did not work, I used a method that works, which I use to log in with.
label_KontoId.setText(myPrivate.getAccountName());
My class's looks like this: In my main i got this code
public void SetId(String AccountId, String kode) {
AccountName = AccountId;
Password = kode;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrivatekunderGUI frame = new PrivatekunderGUI();
frame.setVisible(true);
myPrivate = PR.LogindCheck(AccountName, Password);
} catch (Exception e) {
e.printStackTrace();
}
}
});
label_KontoId.setText(myPrivate.getAccountName());
}
This is not all the code, just what's necessary. The other code is generated for the GUI:
public class Private extends Customers {
private String AccountName;
private String Password;
private int Balance;
private int AccountId;
public Private(String Name, int Number, int Zip, String Address, int Phone,
int Balance, int AccountId, String AccountName, String Password) {
super(Name, Number, Zip, Address, Phone);
this.AccountId = AccountId;
this.Balance = Balance;
this.AccountName = AccountName;
this.Password = Password;
}
public String getAccountName() {
return AccountName;
}
public String getPassword() {
return Password;
}
public int getBalance() {
return Balance;
}
public int getAccountId() {
return AccountId;
}
public void setAccountName(String accountName) {
AccountName = accountName;
}
public void setPassword(String password) {
Password = password;
}
public void setBalance(int balance) {
Balance = balance;
}
public void setAccountId(int accountId) {
AccountId = accountId;
}
void account() {
}
#Override
public String toString() {
return "Private [AccountName=" + AccountName + ", Password=" + Password
+ ", Balance=" + Balance + ", AccountId=" + AccountId
+ ", getName()=" + getName() + ", getNumber()=" + getNumber()
+ ", getZip()=" + getZip() + ", getAddress()=" + getAddress()
+ ", getPhone()=" + getPhone() + "]";
}
}
and my PrivateRegistre looks like this:
public class PrivateRegistre {
private ArrayList<Private> privater = new ArrayList<>();
public PrivateRegistre() {
gem("Driton", 32233223, 2400, "Hallovej 54", 32233223, 543442, 1,
"Driton", "1234");
}
public void gem(String Name, int Number, int Zip, String Address,
int Phone, int Balance, int AccountId, String AccountName,
String Password) {
privater.add(new Private(Name, Number, Zip, Address, Phone, Balance,
AccountId, AccountName, Password));
}
public ArrayList<Private> hentalleprivatekunder() {
return privater;
}
public Private findkunde(int AccountId) {
for (Private privat : privater) {
if (privat.getAccountId() == AccountId) {
return privat;
}
}
return null;
}
public Private LogindCheck(String AccountName, String Password) {
for (Private privat : privater) {
if (privat.getAccountName().equals(AccountName)
&& privat.getPassword().equals(Password)) {
return privat;
}
}
return null;
}
public boolean sletprivatekunde(int AccountId) {
Private privat = findkunde(AccountId);
if (privat == null)
return false;
privater.remove(privat);
return true;
}
#Override
public String toString() {
return "PrivateRegistre [Private Kunder=" + privater + "]";
}
public Private HentLogindOplysninger(String AccountName) {
for (Private privat : privater) {
if (privat.getAccountName().equals(AccountName)) {
return privat;
}
}
return null;
}
}
Because you are returning null in your methods
findkunde(...)
HentLogindOplysninger(...)
LogindCheck(...)
You shouldn't be returning null - return something useful and if you have nothing to return better use void in method return type
myPrivate = PR.LogindCheck(AccountName, Password); here you are getting null beacuse you are returning null in method
public Private LogindCheck(String AccountName, String Password)
& also in
public Private findkunde(int AccountId)
just replacereturn null statement with something that would make sense and can be assigned and then used without resulting into NullPointerException;
Related
I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.
I've been working on a Paypal JSON to Java object converter, using Gson. But, it doesn't generate a full Java object. Seems like this conversion would have already been done, but I couldn't find anything.
My technique is to take the Paypal JSON, do replacements of their non-Java element names, then parse that into a Java object that I've defined.
Here's what the Gson looks like:
Gson gson = new GsonBuilder().serializeNulls().create();
JSONObjFromPaypalTrx jsonPaypalTrx = gson.fromJson(paypalTrx, JSONObjFromPaypalTrx.class);
logger.debug("jsonPaypalTrx: " +jsonPaypalTrx);
paypalTrx is the Paypal JSON after the element names are replaced:
paypalTrx: {"id":"PAYID-LXJIHMI92J52777N04488909","intent":"Sale","state":"approved","cart":"25M35194DL227451S","createTime":"2019-11-18T11:42:41Z","Payer":{"paymentMethod":"paypal","status":"VERIFIED","PayerInfo":{"email":"sb-cject591397#personal.example.com","firstName":"John","middleName":"John","lastName":"Doe","payerId":"5V25373K45VBE","countryCode":"US","ShippingAddress":{"recipientName":"John Doe","line1":"1 Main St","city":"San Jose","state":"CA","postalCode":"95131","countryCode":"US"}}},"Transactions":[{"Amount":{"total":"199.99","currency":"USD","Details":{"subtotal":"199.99","shipping":"0.00","handlingFee":"0.00","insurance":"0.00","shippingDiscount":"0.00"}},"ItemList":{},"RelatedResources":[{"Sale":{"id":"80E26736585579458","state":"completed","paymentMode":"INSTANT_TRANSFER","protectionEligibility":"ELIGIBLE","parentPayment":"PAYID-LXJIHMI92J52777N04488909","createTime":"2019-11-18T11:43:00Z","updateTime":"2019-11-18T11:43:00Z","Amount":{"total":"199.99","currency":"USD","Details":{"subtotal":"199.99","shipping":"0.00","handlingFee":"0.00","insurance":"0.00","shippingDiscount":"0.00"}}}}]}]}
Here's the Java object I've defined:
package com.example;
import java.util.List;
/**
* This JSON Object was derived from a Paypal transaction string.
*/
public class JSONObjFromPaypalTrx{
private String id;
private String intent;
private String state;
private String cart;
private String createTime;
private Payer payer;
private List<Transactions> transactions;
public JSONObjFromPaypalTrx() {
}
public String getId(){
return id;
}
public void setId(String input){
this.id = input;
}
public String getIntent(){
return intent;
}
public void setIntent(String input){
this.intent = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getCart(){
return cart;
}
public void setCart(String input){
this.cart = input;
}
public String getCreateTime(){
return createTime;
}
public void setCreateTime(String input){
this.createTime = input;
}
public Payer getPayer(){
return payer;
}
public void setPayer(Payer input){
this.payer = input;
}
public List<Transactions> getTransactions(){
return transactions;
}
public void setTransactions(List<Transactions> input){
this.transactions = input;
}
public static class ShippingAddress{
private String recipientName;
private String line1;
private String city;
private String state;
private String postalCode;
private String countryCode;
public ShippingAddress() {
}
public String getRecipientName(){
return recipientName;
}
public void setRecipientName(String input){
this.recipientName = input;
}
public String getLine1(){
return line1;
}
public void setLine1(String input){
this.line1 = input;
}
public String getCity(){
return city;
}
public void setCity(String input){
this.city = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getPostalCode(){
return postalCode;
}
public void setPostalCode(String input){
this.postalCode = input;
}
public String getCountryCode(){
return countryCode;
}
public void setCountryCode(String input){
this.countryCode = input;
}
#Override
public String toString() {
return "ShippingAddress [recipientName: " + recipientName + ", line1: " + line1 + ", city: " + city
+ ", state: " + state + ", postalCode: " + postalCode + ", countryCode: " + countryCode + "]";
}
}
public static class PayerInfo{
private String email;
private String firstName;
private String middleName;
private String lastName;
private String payerId;
private String countryCode;
private ShippingAddress shippingAddress;
public PayerInfo() {
}
public String getEmail(){
return email;
}
public void setEmail(String input){
this.email = input;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getMiddleName(){
return middleName;
}
public void setMiddleName(String input){
this.middleName = input;
}
public String getLastName(){
return lastName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getPayerId(){
return payerId;
}
public void setPayerId(String input){
this.payerId = input;
}
public String getCountryCode(){
return countryCode;
}
public void setCountryCode(String input){
this.countryCode = input;
}
public ShippingAddress getShippingAddress(){
return shippingAddress;
}
public void setShippingAddress(ShippingAddress input){
this.shippingAddress = input;
}
#Override
public String toString() {
return "PayerInfo [email: " + email + ", firstName: " + firstName + ", middleName: " + middleName
+ ", lastName: " + lastName + ", payerId: " + payerId + ", countryCode: " + countryCode
+ ", shippingAddress: " + shippingAddress + "]";
}
}
public static class Payer{
private String paymentMethod;
private String status;
private PayerInfo payerInfo;
public Payer() {
}
public String getPaymentMethod(){
return paymentMethod;
}
public void setPaymentMethod(String input){
this.paymentMethod = input;
}
public String getStatus(){
return status;
}
public void setStatus(String input){
this.status = input;
}
public PayerInfo getPayerInfo(){
return payerInfo;
}
public void setPayerInfo(PayerInfo input){
this.payerInfo = input;
}
#Override
public String toString() {
return "Payer [paymentMethod: " + paymentMethod + ", status: " + status + ", payerInfo: " + payerInfo + "]";
}
}
public static class Amount{
private String total;
private String currency;
private Details details;
public Amount() {
}
public String getTotal(){
return total;
}
public void setTotal(String input){
this.total = input;
}
public String getCurrency(){
return currency;
}
public void setCurrency(String input){
this.currency = input;
}
public Details getDetails(){
return details;
}
public void setDetails(Details input){
this.details = input;
}
#Override
public String toString() {
return "Amount [total: " + total + ", currency: " + currency + ", details: " + details + "]";
}
}
public static class ItemList{
public ItemList() {
}
}
public static class Details{
private String subtotal;
private String shipping;
private String handlingFee;
private String insurance;
private String shippingDiscount;
public Details() {
}
public String getSubtotal(){
return subtotal;
}
public void setSubtotal(String input){
this.subtotal = input;
}
public String getShipping(){
return shipping;
}
public void setShipping(String input){
this.shipping = input;
}
public String getHandlingFee(){
return handlingFee;
}
public void setHandlingFee(String input){
this.handlingFee = input;
}
public String getInsurance(){
return insurance;
}
public void setInsurance(String input){
this.insurance = input;
}
public String getShippingDiscount(){
return shippingDiscount;
}
public void setShippingDiscount(String input){
this.shippingDiscount = input;
}
#Override
public String toString() {
return "Details [subtotal: " + subtotal + ", shipping: " + shipping + ", handlingFee: " + handlingFee
+ ", insurance: " + insurance + ", shippingDiscount: " + shippingDiscount + "]";
}
}
public static class Sale{
private String id;
private String state;
private String paymentMode;
private String protectionEligibility;
private String parentPayment;
private String createTime;
private String updateTime;
private Amount amount;
public Sale() {
}
public String getId(){
return id;
}
public void setId(String input){
this.id = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getPaymentMode(){
return paymentMode;
}
public void setPaymentMode(String input){
this.paymentMode = input;
}
public String getProtectionEligibility(){
return protectionEligibility;
}
public void setProtectionEligibility(String input){
this.protectionEligibility = input;
}
public String getParentPayment(){
return parentPayment;
}
public void setParentPayment(String input){
this.parentPayment = input;
}
public String getCreateTime(){
return createTime;
}
public void setCreateTime(String input){
this.createTime = input;
}
public String getUpdateTime(){
return updateTime;
}
public void setUpdateTime(String input){
this.updateTime = input;
}
public Amount getAmount(){
return amount;
}
public void setAmount(Amount input){
this.amount = input;
}
#Override
public String toString() {
return "Sale [id: " + id + ", state: " + state + ", paymentMode: " + paymentMode + ", protectionEligibility: "
+ protectionEligibility + ", parentPayment: " + parentPayment + ", createTime: " + createTime
+ ", updateTime: " + updateTime + ", amount: " + amount + "]";
}
}
public static class RelatedResources{
private Sale sale;
public RelatedResources() {
}
public Sale getSale(){
return sale;
}
public void setSale(Sale input){
this.sale = input;
}
#Override
public String toString() {
return "RelatedResources [sale: " + sale + "]";
}
}
public static class Transactions{
private Amount amount;
private ItemList itemList;
private List<RelatedResources> relatedResources;
public Transactions() {
}
public Amount getAmount(){
return amount;
}
public void setAmount(Amount input){
this.amount = input;
}
public ItemList getItemList(){
return itemList;
}
public void setItemList(ItemList input){
this.itemList = input;
}
public List<RelatedResources> getRelatedResources(){
return relatedResources;
}
public void setRelatedResources(List<RelatedResources> input){
this.relatedResources = input;
}
#Override
public String toString() {
return "Transactions [amount: " + amount + ", itemList: " + itemList + ", relatedResources: "
+ relatedResources + "]";
}
}
#Override
public String toString() {
return "JSONObjFromPaypalTrx [id: " + id + ", intent: " + intent + ", state: " + state + ", cart: " + cart
+ ", createTime: " + createTime + ", payer: " + payer + ", transactions: " + transactions + "]";
}
}
Here's a log of jsonPaypalTrx:
jsonPaypalTrx: JSONObjFromPaypalTrx [id: PAYID-LXJIHMI92J52777N04488909, intent: Sale, state: approved, cart: 25M35194DL227451S, createTime: 2019-11-18T11:42:41Z, payer: null, transactions: null]
Is the incomplete jsonPaypalTrx due to my use of inner classes inside JSONObjFromPaypalTrx? Splitting each inner class into separate Java files would be awkward for me to do.
Thanks for helping.
Bob
Given JSON payload uses mixed naming convention: camel case and UPPER_CAMEL_CASE for JSON Objects. So, you need to implement your own FieldNamingStrategy:
class PayPalFieldNamingStrategy implements FieldNamingStrategy {
#Override
public String translateName(Field f) {
return f.getType() == String.class ? f.getName() : FieldNamingPolicy.UPPER_CAMEL_CASE.translateName(f);
}
}
And register it like below:
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(new PayPalFieldNamingStrategy())
.create();
Or, for each object declare name like below:
#SerializedName("Payer")
private Payer payer;
Make your member classes static so that they don't need an outer class reference when they're constructed.
Like: public static class ShippingAddress.
Gson likely doesn't know how to constructor inner classes, but it will know how to construct static member classes.
Below is the stacktrace of the error:
org.springframework.orm.hibernate3.HibernateSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
Caused by: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:217)
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:240)
Below is my POJO class :
public static final class MemberName implements java.io.Serializable
{
/**
*
*/
private static final long serialVersionUID = 3832626162173359411L;
private String firstname;
private String lastname;
private String gender;
private String dexterity;
private String matchPreference;
private String tournamentEntry;
/*private Double rating;
private Double minRating=Double.valueOf(2.5);
private Double maxRating=Double.valueOf(5.0);*/
private Integer rating=null;
private Integer minRating=null;
private Integer maxRating=Integer.valueOf(5);
private Integer maxHandicap = Integer.valueOf(100);//Integer.valueOf(6);
private Integer minHandicap = null;
public MemberName() {
}
public String getFirstname() { return this.firstname; }
public void setFirstname(String name) { this.firstname = name; }
public String getLastname() { return this.lastname; }
public void setLastname(String name) { this.lastname = name; }
public Integer getMaxHandicap() { return this.maxHandicap; }
public void setMaxHandcap(Integer d) { this.maxHandicap = d; }
public Integer getMinHandicap() { return this.minHandicap; }
public void setMinHandcap(Integer d) { this.minHandicap = d; }
public String getGender() { return this.gender;}
public void setGender(String gender) {this.gender = gender;}
public String getDexterity() {return this.dexterity;}
public void setDexterity(String dexterity) {this.dexterity = dexterity;}
public String getMatchPreference() {return this.matchPreference;}
public void setMatchPreference(String matchPreference) {this.matchPreference = matchPreference;}
public String getTournamentEntry() {return this.tournamentEntry;}
public void setTournamentEntry(String tournamentEntry) {this.tournamentEntry = tournamentEntry;}
public Integer getRating() {return this.rating;}
public void setRating(Integer r) {this.rating = r;}
public Integer getMinRating() {return this.minRating;}
public void setMinRating(Integer minR) {this.minRating = minR;}
public Integer getMaxRating() {return this.maxRating;}
public void setMaxRating(Integer maxR) {this.maxRating = maxR;}
public boolean isValidSearch()
{
return (null != this.firstname) ||
(null != this.lastname) ||
(null != this.maxRating) ||
(null != this.minRating)||
(null != this.rating)||
(null != this.gender) ||
(null != this.dexterity) ||
(null != this.matchPreference)||
(null != this.tournamentEntry);
}
#Override
public String toString() {
return "MemberName [firstname=" + firstname + ", lastname="
+ lastname + ", gender=" + gender + ", dexterity="
+ dexterity + ", matchPreference=" + matchPreference
+ ", tournamentEntry=" + tournamentEntry + ", rating="
+ rating + ", minRating=" + minRating + ", maxRating="
+ maxRating + "]";
}
}
and I'm using hibernate 3 to fetch the data from User table which is a hibernate pojo class-
public List<User> findUsers(Long cityId, String firstName, String
lastName,
String gender, Double rating, Double minRating, Double maxRating,
String dexterity, String matchPreference, String tournamentEntry) {
StringBuilder sb = new StringBuilder();
if (null != cityId) {
sb.append("u.registeredCity.id=").append(cityId).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
}
if (isNotEmpty(firstName)) {
if (sb.length() > 0) {
sb.append("and "); //$NON-NLS-1$
}
sb.append("u.firstName like '").append(firstName).append("%' ");
}
if (isNotEmpty(lastName)) {
if (sb.length() > 0) {
sb.append("and "); //$NON-NLS-1$
}
sb.append("u.lastName like '").append(lastName).append("%'");
}
sb.append(" order by u.firstName, u.lastName");
if (sb.length() > 0) {
sb.insert(0, "where "); //$NON-NLS-1$
}
sb.insert(0, "from User u "); //$NON-NLS-1$
this.log.info("SQL from findUsers method is::"+sb.toString());
return getHibernateTemplate().find(sb.toString());
}
I have written a class Form. An array of 10 Strings is the only parameter in the constructor. How can I create an instance of the class? I'm sure there are other problems in my setters and getters but I cant test them until I fix this.
public class FormLab {
public static void main(String[]args){
Form f1 = new Form(String webForm);
System.out.println(print(String[] webForm));
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}
}
public class Form {
String[] webForm = new String[10];
private String userID;
private String pw;
private String pw2;
private String email;
private String name;
private String address;
private String city;
private String state;
private String zip;
private String telephone;
//constructor
public Form(String[] webForm){
//filling array with field values
webForm[0] = "0123456789";
webForm[1] = "java123";
webForm[2] = "java123";
webForm[3] = "luke.skywalker#jedi.com";
webForm[4] = "Luke Skywalker";
webForm[5] = "1234 The Force Way";
webForm[6] = "Rome";
webForm[7] = "GA";
webForm[8] = "30161";
webForm[9] = "7065551234";
}
public boolean getEmptyFields() {
//boolean empty = false;
for(int i = 0; i < webForm.length; i++){
if(webForm[i]!= null){
return true;
}
}
return false;
}
public String getUserID(){
return userID;
}
public void setUserId(String userID){
this.userID = userID;
}
public String getPw(){
return pw;
}
public void setPw(String pw){
this.pw = pw;
}
public String getPw2(){
return pw2;
}
public void setPw2(String pw2){
this.pw2 = pw2;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
public String getZip(){
return userID;
}
public void setZip(String zip){
this.zip = zip;
}
public String getTelephone(){
return telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public int getCharNum(String userID) {
int userLength = 0;
//userID.length();
return userLength;
}
public boolean getPwCheck() {
boolean check = pw.equalsIgnoreCase(pw2);
// pw.equalsIgnoreCase(pw2);
return check;
}
public boolean getEmailCheck(String email) {
if(email.contains("#") && email.contains(".")){
return true;
}
return false;
}
public static void getPrint(String[] webForm) {
System.out.println(webForm.toString());
}
}
Use method arraycopy.
public Form(String[] webForm){
System.arraycopy(webForm, 0, this.webForm, 0, webForm.length);
}
The constructor takes a string array as argument, but you are passing it a string, try:
myList = new String[];
myForm = new Form(myList);
You need to declare your array before putting it as a parameter as follow:
public class FormLab {
public static void main(String[]args){
String webForm = new String[10];
Form f1 = new Form(webForm);
/*System.out.println(print(String[] webForm)); THIS IS WRONG*/
/*TO PRINT THE VALUES IN THE ARRAY YOU NEED TO WRITE A METHOD IN UR
FORM CLASS THAT WILL LOOP THRU UR VARIABLE AND PRINT*/
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is Java, using BlueJ.
I have four classes called Person, Letter, Address and PhoneNumber. In each, I override the toString() method to return a concatenated string of the values I want from the class. When calling the Letter toString(), it is returning null on all values.
The idea is to use the hard coded information, pass it into the appropriate class, and return it in a standard letter format.
Am I headed in the right direction for printing out the information hard coded, or should I go a different route? This is a homework problem, but I feel I have hit a brick wall.
Here are the classes:
public class Person
{
private static String aPerson;
private String first;
private String middle;
private String last;
private Address address;
private PhoneNumber phone;
public String getFirst()
{
return this.first;
}
public void setFirst(String FirstName)
{
this.first = FirstName;
}
public String getMiddle()
{
return this.middle;
}
public void setMiddle(String MiddleName)
{
this.middle = MiddleName;
}
public String getLast()
{
return this.last;
}
public void setLast(String LastName)
{
this.last = LastName;
}
public Address getMyAddress()
{
return this.address;
}
public void setMyAddress(Address Address)
{
this.address = Address;
}
public PhoneNumber getMyPhoneNum()
{
return this.phone;
}
public void setMyPhoneNum(PhoneNumber Number)
{
this.phone = Number;
}
public Person()
{
aPerson = getFirst() + getMiddle() + getLast() + getMyAddress() +
getMyPhoneNum();
}
public String toString()
{
return aPerson;
}
}
PhoneNumber:
public class PhoneNumber
{
private String number;
private int areaCode = 0;
private int phonePrefix = 0;
private int phoneLineNum = 0;
private int phoneExtension = 0;
public String getNumber()
{
return number;
}
public void setNumber(String Number)
{
number = Number;
}
public int getAreaCode()
{
return areaCode;
}
public void setAreaCode(int AreaCode)
{
areaCode = AreaCode;
}
public int getPrefix()
{
return phonePrefix;
}
public void setPrefix(int Prefix)
{
phonePrefix = Prefix;
}
public int getPhoneLineNumber()
{
return phoneLineNum;
}
public void setLineNum(int PhoneNumber)
{
phoneLineNum = PhoneNumber;
}
public int getExtension()
{
return phoneExtension;
}
public void setExtension(int Extension)
{
phoneExtension = Extension;
}
}
Address:
public class Address
{
private String state;
private String anAddress;
private String address;
private String city;
private int zip = 0;
public String getState()
{
return state;
}
public void setState(String State)
{
state = State;
}
public String getAddress()
{
return address;
}
public void setAddress(String Address)
{
address = Address;
}
public String getCity()
{
return city;
}
public void setCity(String City)
{
city = City;
}
public int getZip()
{
return zip;
}
public void setZip(int Zip)
{
zip = Zip;
}
public Address()
{
anAddress = getState() + getAddress() + getCity() + getZip();
}
public String toString()
{
return this.anAddress;
}
}
Letter:
public class Letter
{
private Person to;
private Person from;
private String body;
private String finishedLetter;
public Person getTo()
{
return to;
}
public void setTo(Person newValue)
{
to = newValue;
}
public Person getFrom()
{
return from;
}
public void setFrom(Person newValue)
{
from = newValue;
}
public String getBody()
{
return body;
}
public void setBody(String newValue)
{
body = newValue;
}
public Letter()
{
finishedLetter = getTo() + " \n" + getFrom() + " \n" + getBody();
}
public String toString()
{
return finishedLetter;
}
}
And main:
public class MainClass
{
public static void main(String args[])
{
PhoneNumber phone1 = new PhoneNumber();
phone1.setAreaCode(417);
phone1.setPrefix(447);
phone1.setLineNum(7533);
phone1.setExtension(0);
PhoneNumber phone2 = new PhoneNumber();
phone2.setAreaCode(210);
phone2.setPrefix(336);
phone2.setLineNum(4343);
phone2.setExtension(9850);
Address address1 = new Address();
address1.setState("MO");
address1.setAddress("1001 East Chestnut Expressway");
address1.setCity("Springfield");
address1.setZip(65807);
Address address2 = new Address();
address2.setState("TX");
address2.setAddress("4800 Calhoun Road");
address2.setCity("Houston");
address2.setZip(77004);
Person person1 = new Person();
person1.setFirst("Shane");
person1.setMiddle("Carroll");
person1.setLast("May");
person1.setMyAddress(address1);
person1.setMyPhoneNum(phone1);
Person person2 = new Person();
person2.setFirst("Ted");
person2.setMiddle("Anthony");
person2.setLast("Nugent");
person2.setMyAddress(address2);
person2.setMyPhoneNum(phone2);
Letter aLetter = new Letter();
aLetter.setTo(person2);
aLetter.setFrom(person1);
aLetter.setBody("This is the body");
System.out.println(aLetter.toString());
}
}
Your Letter constructor is calling methods such as getTo() and getFrom() before those fields have been filled. Don't do this since your finishedLetter String will never be correctly "finished". i.e.,
public Letter()
{
finishedLetter = getTo() + " \n" + getFrom() + " \n" + getBody();
}
will always result in null + "\n" + null + "\n" + null
Perhaps that sort of code should be in the toString() method instead.
When your letter is constructed using new Letter(), it initializes its instance field finishedLetter with several null values. Because to, from, and body haven't yet been set with their corresponding setters, their getters return null, resulting in finishedLetter being equal to "null \nnull \nnull".
To fix this, I one approach is to define the finishedLetter in the toString() method itself. This will both fix the issue and take a more object-oriented approach to the program design.
// remove constructor (if you wish) and finishedLetter field
public String toString() {
return getTo() + " \n" + getFrom() + " \n" + getBody();
}
An even better approach is to require to, from, and body, as parameters in the Letter constructor.
// remove finishedLetter field
public Letter(Person to, Person from, String body) {
this.to = to;
this.from = from;
this.body = body;
}
public String toString() {
return getTo() + " \n" + getFrom() + " \n" + getBody();
}