How to print contents of a class object by field? - java

I have a POJO class, Location that is used to map a JSON file to a class using Jackson. The current implementation can print out every Location object in the class by calling,Location's toString() but I'm wondering how I can print for example, just the location with id= "2", which would be name="Desert"
At the moment, I use a toString method like this to print all the contents of Location:
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
Does anyone know how I can print specific locations within the Location object based on a field id?
This is an example of what is stored in the Location class when I call toString() on it:
http://hastebin.com/eruxateduz.vhdl
An example of one of the Locations within the Location object:
[Location [location=null, id=1, description=You are in the city of Tiberius. You see a long street with high buildings and a castle.You see an exit to the south., weight=100, name=Tiberius, exit=[Exit [title=Desert, direction=South]]]
This is the POJO location class I use to map the JSON fields to the class:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isGoalLocation() {
return goalLocation;
}
public void setGoalLocation(boolean goalLocation) {
this.goalLocation = goalLocation;
}
public int getApproximateDistanceFromGoal() {
return approximateDistanceFromGoal;
}
public void setApproximateDistanceFromGoal(int approximateDistanceFromGoal) {
this.approximateDistanceFromGoal = approximateDistanceFromGoal;
}
public Location getParent() {
return parent;
}
public void setParent(Location parent) {
this.parent = parent;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
}

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
You need the above dependency to define predicate unless you want to do it on your own.
public class Location {
private int id;
// more stuff here
private Predicate<Integer> filter;
public Location() {
this.filter = TruePredicate.INSTANCE;
}
public Location(int idFilter) {
this.filter = new EqualPrediate(idFilter);
}
public String toString() {
StringBuilder buffer = new StringBuilder();
if(filter.apply(this.id)) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}
}
This code is a simplified Visitor Pattern where the
'Visitor' -> your predicate
'this' -> 'this.id'
This works because your toString() is invoking the toString() of the nested Location objects which also have their predicates for filtering set.
If you aren't in control of their construction where you can propogate the filter then you can take this approach:
public String toString() {
StringBuilder buffer = new StringBuilder();
int i = 0;
for(Location l = this; i < locations.length; l = locations[i++])
if(filter.apply(l.id) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}

Stream.of(location).filters(l -> l.getId() == 2).foreach(System.out::println);
Does that work?

You can have a try with gson, which inputs a object and outputs a JSON or in the opposite side.
After u make the object a JSONObject, you can ergodic the JSON in order to ergodic object.

Related

How do I get an array value instead of reference from ObjectMapper in Jackson?

I am trying to get a result from an API response and am able to map everything except for columnHeaders, which is an array of ColumnHeaders. I am instead getting a reference to an array. The code is below.
Response Class
public class Response {
#JsonProperty("searchApiFormatVersion")
private String searchApiFormatVersion;
#JsonProperty("searchName")
private String searchName;
#JsonProperty("description")
private String description;
#JsonProperty("columnHeaders")
private ColumnHeader[] columnHeaders;
public Response(String searchApiFormatVersion, String searchName, String description,
ColumnHeader[] columnHeaders) {
this.searchApiFormatVersion = searchApiFormatVersion;
this.searchName = searchName;
this.description = description;
this.columnHeaders = columnHeaders;
}
public Response(){
}
public String getSearchApiFormatVersion() {
return searchApiFormatVersion;
}
public void setSearchApiFormatVersion(String searchApiFormatVersion) {
this.searchApiFormatVersion = searchApiFormatVersion;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ColumnHeader[] getColumnHeaders() {
return columnHeaders;
}
public void setColumnHeaders(ColumnHeader[] columnHeaders) {
this.columnHeaders = columnHeaders;
}
#Override
public String toString() {
return "Response{" +
"searchApiFormatVersion='" + searchApiFormatVersion + '\'' +
", searchName='" + searchName + '\'' +
", description='" + description + '\'' +
", totalRowCount=" + totalRowCount +
", returnedRowCount=" + returnedRowCount +
", startingReturnedRowNumber=" + startingReturnedRowNumber +
", basetype='" + basetype + '\'' +
", columnCount=" + columnCount +
", columnHeaders=" + columnHeaders +
'}';
}
}
ColumnHeader class
public class ColumnHeader {
#JsonProperty("text")
private String text;
#JsonProperty("dataType")
private String dataType;
#JsonProperty("hierarchy")
private int hierarchy;
#JsonProperty("parentName")
private String parentName;
#JsonProperty("isEntity")
private Boolean isEntity;
#JsonProperty("isEset")
private Boolean isEset;
public ColumnHeader(String text, String dataType, int hierarchy, String parentName, Boolean isEntity, Boolean isEset) {
this.text = text;
this.dataType = dataType;
this.hierarchy = hierarchy;
this.parentName = parentName;
this.isEntity = isEntity;
this.isEset = isEset;
}
public ColumnHeader(){
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public int getHierarchy() {
return hierarchy;
}
public void setHierarchy(int hierarchy) {
this.hierarchy = hierarchy;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Boolean getEntity() {
return isEntity;
}
public void setEntity(Boolean entity) {
isEntity = entity;
}
public Boolean getEset() {
return isEset;
}
public void setEset(Boolean eset) {
isEset = eset;
}
#Override
public String toString() {
return "ColumnHeader{" +
"text='" + text + '\'' +
", dataType='" + dataType + '\'' +
", hierarchy=" + hierarchy +
", parentName='" + parentName + '\'' +
", isEntity=" + isEntity +
", isEset=" + isEset +
'}';
}
}
Service Class
public class BudgetEffortResponseService {
Logger logger = LoggerFactory.getLogger(Response.class);
public Response getResponseFromStringJsonApiResponse(String stringJsonResponse) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); //Used to map objects from JSON values specified in Award under #JsonProperty annotation
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JSONObject stringJsonResponseTurnedIntoJsonObject = new JSONObject(stringJsonResponse);
logger.info("stringJsonResponseTurnedIntoJsonObject: " + stringJsonResponseTurnedIntoJsonObject);
return objectMapper.readValue(stringJsonResponseTurnedIntoJsonObject.toString(), Response.class);
}
}
Main Class
#SpringBootApplication
public class EtlApplication {
public static final String API_USERNAME = System.getenv("API_USERNAME");
public static final String API_PASSWORD = System.getenv("API_PASSWORD");
public static final String API_PREFIX = System.getenv("API_PREFIX");
public static final String API_PATH = System.getenv("API_PATH");
public static void main(String[] args) throws URISyntaxException, JsonProcessingException {
Logger logger = LoggerFactory.getLogger(EtlApplication.class);
logger.info("--------------------Starting process--------------------");
AwardRepository awardRepository = new AwardRepository();
AwardService awardService = new AwardService();
ApiResponseRowService apiResponseRowService = new ApiResponseRowService();
ApiResponseRepository apiResponseRepository = new ApiResponseRepository();
BudgetEffortResponseService budgetEffortResponseService = new BudgetEffortResponseService();
Date startDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 1).getTime();
Date endDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 2).getTime();
logger.info("============Starting BudgetEffort API pull from Huron===============");
HttpResponse<String> budgetEffortHttpResponse = apiResponseRepository.getHttpResponseFromApi(startDateForApiPull,
endDateForApiPull, 1, -1, API_PREFIX, API_PATH,
API_USERNAME, API_PASSWORD);
logger.info("BudgetEffortHttpResponse: " + budgetEffortHttpResponse);
logger.info("============End of BudgetEffort API pull from Huron===============");
//Get body of http response string
String budgetEffortResponseString = budgetEffortHttpResponse.body();
logger.info("BudgetEffortResponseString: " + budgetEffortResponseString);
Response budgetEffortResponse = budgetEffortResponseService.getResponseFromStringJsonApiResponse(budgetEffortResponseString);
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
logger.info("--------------------End of process--------------------");
}
}
The response. I'm noticing that I'm getting the reference to the array for columnHeaders and not the values. How would I get the values? Thank you.
BudgetEffortResponse: Response{searchApiFormatVersion='1.0', searchName='Personnel Details for Authorized allocations on Active Awards', description='', columnHeaders=[Lcom.example.etl.entity.budgetEffort.ColumnHeader;#7a7471ce}
The response you get is ok. And also the Array is good. The line
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
uses an indirect cast to String of the Object budgetEffortResponse. In this case all toString() methods of the objects are called. What you need to do in order to print out the Objects is to implement/add the toString() method in the class com.example.etl.entity.budgetEffort.ColumnHeader
Update:
As the toString method is already implemented, the above is partially wrong. But there is a way to use a setting of the ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(budgetEffortResponse);
logger.info("BudgetEffortResponse: " + json);

Converting Paypal Checkout Transaction to a Java Object?

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.

Simple database on Java

I've got a task to make a simple database on a topic "basketball team" with functionality such as: deleting by ID, inserting new data, modification of information, printing all data from a file. All information should be written in a file.
I've already created createTeam() method that makes a kind of template of my default data that writes in a file.
Basically, after that, I've got trouble in deleteByID() method with deleting exact data that I need, so I'm asking you for a help
My code:
import java.io.*;
public class ChicagoBulls {
static class Player{
private int Id;
private int Age;
private String Name;
private String Surname;
private int Height;
private int Salary;
private String KPI;
private String Shoes;
private int Goals;
Player(int id, int age, String name, String surname, int height,
int salary, String kpi, String shoes, int goals) {
Goals = goals;
Id = id;
Age = age;
Name = name;
Surname = surname;
Height = height;
Salary = salary;
KPI = kpi;
Shoes = shoes;
}
public String getShoes() {
return Shoes;
}
public void setShoes(String shoes) {
Shoes = shoes;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
public String getKPI() {
return KPI;
}
public void setKPI(String KPI) {
this.KPI = KPI;
}
public int getHeight() {
return Height;
}
public void setHeight(int height) {
Height = height;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public int getGoals() {
return Goals;
}
public void setGoals(int goals) {
Goals = goals;
}
}
public void createTeam(int quantity) throws Exception {
File newFile = new File("NewFile.txt");
FileWriter newFileReader = new FileWriter(newFile);
BufferedWriter bufferedWriter = new BufferedWriter(newFileReader);
bufferedWriter.write("|ID|\t"
+ "| AGE |\t"
+ "| NAME |\t"
+ "| SURNAME |\t"
+ "| HEIGHT |\t"
+ "| SALARY |\t"
+ "| KPI |\t"
+ "| SHOES |\t"
+ "| Goals |\t\n");
int counter = quantity;
for (int i = 0; i <= quantity; i++) {
Player defaultPlayer = new Player(i, 19, "DefName", "DefSurname", 180, 6000, "Good", "Nike", 0);
if (defaultPlayer.getId()<=9) {
bufferedWriter.write("|0" + defaultPlayer.getId() + "|\t");
bufferedWriter.write("|" + defaultPlayer.getAge() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getName() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSurname() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getHeight() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSalary() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getKPI() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getShoes() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getGoals() + " |\t");
}else{
bufferedWriter.write("|" + defaultPlayer.getId() + "|\t");
bufferedWriter.write("|" + defaultPlayer.getAge() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getName() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSurname() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getHeight() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSalary() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getKPI() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getShoes() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getGoals() + " |\t");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
newFileReader.close();
}
public void deleteByID(int id) throws Exception {
FileReader file = new FileReader("NewFile.txt");
BufferedReader bufferedReader = new BufferedReader(file);
String idLine = bufferedReader.readLine();
int idIndex = idLine.indexOf(id);
int nextIdIndex = idLine.indexOf(id + 1);
}
}
Main
public class Main {
public static void main(String[] args) throws Exception {
ChicagoBulls team = new ChicagoBulls();
team.createTeam(30);
}
}
Thank you in advance.
I think the logic behind your execution is a bit too complicated to be understood without further explanations on your part. From what i gathered on your needs, i would suggest creating multiple constructors for the Player class - one requiring no input and returning a "Default" player with default characteristics, the other one with the ability to specify goals, shoes, etc.
After that, each of your teams can be represented as a Set<> of players. This would make iterating for each of the elements (players) easier, as well as provide a natural way of removing players from the team. You can read more about the implementation of this structure in the Java documentation here.

overriding tostring() method and passing object reference without getting hash

I'm trying to override the toString() method and print without the hash. When I use my tostring() method when trying to print it requires me to create another object like asset server = new asset();. When I do this and use just server it returns the default constructor or it gives an error when I use server[i]. The code I have written returns this:
`ant -f C:\\Users\\kalle\\Documents\\NetBeansProjects\\assign7 -
Dnb.internal.action.name=run run
init:
Deleting: C:\Users\kalle\Documents\NetBeansProjects\assign7\build\built-
jar.properties
deps-jar:
Updating property file:
C:\Users\kalle\Documents\NetBeansProjects\assign7\build\built-
jar.properties
compile:
run:
server switch etc.
0
vendor model number
serial number
1
driver.asset#15db9742
server
server0
10
a1
1
driver.asset#15db9742
server
server1
20
a2
1
BUILD SUCCESSFUL (total time: 0 seconds)`
Here is my code:`
package driver;
public class Driver {
public static void main(String[] args) {
int i;
asset basic = new asset();
asset[] server = new asset[2];
server[0]= new asset("server", 10, "server0", "a1", 1);
server[1]= new asset("server", 20, "server1", "a2",1);
for (i=0;i<server.length;i++){
System.out.println(basic);
System.out.println(server[i].Type);
System.out.println(server[i].Name);
System.out.println(server[i].ID);
System.out.println(server[i].Serial);
System.out.println(server[i].PID);
}
}
}
public class asset {
String Type;
int ID;
String Name;
String Serial;
int PID;
int i;
public String getType(){
return Type;
}
public void setType(String Type){
this.Type = Type;
}
public int getID(){
return ID;
}
public void setID(int getid){
Integer.toString(ID);
this.ID= ID;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public String getSerial(){
return Serial;
}
public void setSerial(String Serial){
this.Serial = Serial;
}
public int getPID() {
return PID;
}
public void setPID(int getPID) {
Integer.toString(PID);
this.PID= PID;
}
public asset(){
Name ="vendor model number";
ID =0;
Serial ="serial number";
Type ="server switch etc.";
PID =1;
System.out.println( Type + "\n " + ID + "\n " + Name + "\n " + Serial + "\n " + PID + "\n ");}
asset(String Type, int ID, String Name, String Serial, int PID){
this.Type= Type;
this.Name= Name;
this.PID= PID;
this.Serial= Serial;
this.ID= ID;
}
public String toString (asset[] a){
getType();
getID();
setID(ID);
getName();
getSerial();
getPID();
setPID(PID);
return this.Type + " " + this.ID + " " + this.Name + " " + this.Serial + " " + this.PID + " ";
}
}
How do i get rid of the "driver.asset#15db9742".
The correct way to override the toString method is to have the following structure :
public String toString(){
// return String type
}
For you (call getXY() does nothing alone) :
public String toString (){
return this.Type + " " + this.ID + " " + this.Name + " " + this.Serial + " " + this.PID + " ";
}
Also, to follow conventions, you'd better :
name classes in CamelCase : asset -> Asset
name attributs (&parameter&variables) follow camelCase : type, id, name, pid
Try this:
int i;
asset basic = new asset();
asset[] server = new asset[2];
server[0]= new asset("server", 10, "server0", "a1", 1);
server[1]= new asset("server", 20, "server1", "a2",1);
System.out.println(basic); // just delete this line.
for (i=0;i<server.length;i++)
{
System.out.println(server[i].Type);
System.out.println(server[i].Name);
System.out.println(server[i].ID);
System.out.println(server[i].Serial);
System.out.println(server[i].PID);}
}
You kept printing out the value of basic, that's probably why it churned out the the string hash name instead of the actual stored value. Just take the System.out.println(basic); out of the for loop? Even better, delete the line altogether!

Avoiding recursion in toString method

this is my huge mindblowing problem with a Java exercise. So, we've got this:
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate
}
and our goal is to overwrite toString method by cutting fields which may lead to recursive infinity. Finally it's supposed to look like a printed object with a name, age, boss and subordinate.
Employee[age=30,name='Mike',boss=Employee[age=45,name='Ann'], subordinate=[Employee[age=25,name='Jimmy']]]
Well, I tried and found that i have no clue how to deal with toString overriding:
import java.util.ArrayList;
import java.util.List;
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
public CyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
public static void main(String[] args) {
CyclicEmployee Mike = new CyclicEmployee(33,"Mike");
Mike.boss = new CyclicEmployee(44,"Ann");
Mike.subordinate = new ArrayList<CyclicEmployee>();
Mike.subordinate.add(new CyclicEmployee(24,"Jim"));
System.out.println(Mike.toString());
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + boss +
", subordinate=" + subordinate +
'}';
}
}CyclicEmployee{age=33, name='Mike', boss=CyclicEmployee{age=44, name='Ann', boss=null, subordinate=null}, subordinate=[CyclicEmployee{age=24, name='Jim', boss=null, subordinate=null}]}
It seems like I should cut all the "null" fields here, but I can't find the way out.
If I understand correctly, you do not want to print null CyclicEmployee objects. You can check if boss and subordinates are null and then if they are skip them in toString(). Since all of them are same type, this method will work for all of them.
#Override
public String toString() {
String str = "";
str = "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'';
if (boss != null) {
str += ", boss=" + boss;
}
if (subordinate.size() != 0) {
str += ", subordinate=" + subordinate;
}
str += '}';
return str;
}
Consider using existing data structure like this or this instead.
But if you really want to use your code, you can create a NonCyclicEmployee class
private static class NonCyclicEmployee {
private int age;
private String name;
public NonCyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
And use it in your toString() of CyclicEmployee.
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
private NonCyclicEmployee ncBoss;
private List<NonCyclicEmployee> ncSubordinate ;
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + ncBoss +
", subordinate=" + ncSubordinate +
'}';
}
And create a method addBoss() and addSubordinate() to create both bosses (boss and ncBoss) and both subordinate at the same time.

Categories