hi guys I have created a basket field in this browser class but, however I now need to declare this basket field in the browser class as arraylist collection class object but cant figure out how to do this, below is my code so far
/**
* Write a description of class Browser here.
*
* #author (johnson)
* #version (10/12/13)
*/
public class Browser
{
// instance variables - replace the example below with your own
private int iD;
private String email;
private int yearOfBirth;
private boolean memberID;
private WineCase wineCase;
private boolean loggedIn;
private Website website;
private boolean discount;
List<Boolean> basketList = new ArrayList<Boolean>();
/**
* Constructor for objects of class Browser
*/
public Browser()
{
// initialise instance variables
wineCase = null;
website = null;
iD = 00065;
yearOfBirth = 1992;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = 0;
email = newEmail;
yearOfBirth = newYearOfBirth;
loggedIn = false;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(int newID, String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = newID;
email = newEmail;
yearOfBirth = newYearOfBirth;
memberID = true;
discount = false;
}
/**
* returns the ID
*/
public int getId()
{
return iD;
}
/**
* gets the email of the browser class
*/
public String getEmail()
{
return email;
}
public boolean getDiscount()
{
return discount;
}
/**
* gets the yearOfBirth for the browser class
*/
public int yearOfBirth()
{
return yearOfBirth;
}
public double getWineCost()
{
return wineCase.getWineCost();
}
/**
* returns
*/
public void setLoginStatus(boolean status)
{
loggedIn = status;
}
/**
* returns
*/
public void selectWineCase(WineCase winecase)
{
wineCase = winecase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+winecase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
/**
* returns
*/
public void payForWine()
{
website.checkout(this);
}
public void setId()
{
iD = 999;
}
public void setWebSite(Website website)
{
this.website = website;
}
public void setDiscount(boolean discount)
{
this.discount = discount;
}
}
any answers or replies would be greatly appreciated
Try this out
List<Boolean> basketList = new ArrayList<Boolean>();
That must not be boolean as boolean is a primitive type not a collection of Objects.
what you need to do is:
ArrayList basket = new ArrayList();
Or if you need a collection of Boolean Objects (still not boolean) you can do:
ArrayList basket = new ArrayList();
A list of Boolean(s)?
java.util.List<Boolean> basketAl = new java.util.ArrayList<Boolean>();
And I urge you to add a toString method to your class
// Something like this...
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(iD).append(" ").append(email).append(" ");
sb.append(yearOfBirth).append(" ").append(memberID).append(" ");
sb.append(wineCase).append(" ").append(loggedIn).append(" ");
sb.append(website).append(" ").append(discount).append(" ");
sb.append(Basket);
return sb.toString();
}
It's a bit hard to tell what you're doing but declare this at the top of your class. Also, don't forget to import packages java.util.ArrayList and import java.util.List.
private List<Boolean> baskets = new ArrayList<Boolean>();
This will replace the previous declaration of:
private boolean Basket;
Related
I want add column to grid, when i click to button ("backBtn"). Then i get the value from the textfield ("filterText"), and that will be the name of the new column. Who can help me? The code is from tutorial, but i need add the new feature here. Thanks ! You can find my code in attachment. Grid is in class "MyUI"
This is clas Customer
package my.vaadin.app;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Date;
/**
* A entity object, like in any other Java application. In a typical real world
* application this could for example be a JPA entity.
*/
#SuppressWarnings("serial")
public class Customer implements Serializable, Cloneable {
private Long id;
private String firstName = "";
private String datum = "";
private String lastName = "";
private LocalDate birthDate;
private CustomerStatus status;
private String email = "";
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* Get the value of email
*
* #return the value of email
*/
public String getEmail() {
return email;
}
/**
* Set the value of email
*
* #param email
* new value of email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get the value of status
*
* #return the value of status
*/
public CustomerStatus getStatus() {
return status;
}
/**
* Set the value of status
*
* #param status
* new value of status
*/
public void setStatus(CustomerStatus status) {
this.status = status;
}
/**
* Get the value of birthDate
*
* #return the value of birthDate
*/
public LocalDate getBirthDate() {
return birthDate;
}
/**
* Set the value of birthDate
*
* #param birthDate
* new value of birthDate
*/
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
/**
* Get the value of lastName
*
* #return the value of lastName
*/
public String getLastName() {
return lastName;
}
/**
* Set the value of lastName
*
* #param lastName
* new value of lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Get the value of firstName
*
* #return the value of firstName
*/
public String getFirstName() {
return firstName;
}
/**
* Set the value of firstName
*
* #param firstName
* new value of firstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getDatum() {
return datum;
}
/**
* Set the value of firstName
*
* #param firstName
* new value of firstName
*/
public void setDatum(String datum) {
this.datum = datum;
}
public boolean isPersisted() {
return id != null;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this.id == null) {
return false;
}
if (obj instanceof Customer && obj.getClass().equals(getClass())) {
return this.id.equals(((Customer) obj).id);
}
return false;
}
#Override
public int hashCode() {
int hash = 5;
hash = 43 * hash + (id == null ? 0 : id.hashCode());
return hash;
}
#Override
public Customer clone() throws CloneNotSupportedException {
return (Customer) super.clone();
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
This is clas MyUI
package my.vaadin.app;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.swing.text.TableView;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.SelectionMode;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.components.grid.HeaderCell;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of a html page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {#link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
#Theme("mytheme")
public class MyUI extends UI {
private CustomerService service = CustomerService.getInstance();
private Grid<Customer> grid = new Grid<>(Customer.class);
private TextField filterText = new TextField();
// private CustomerForm form = new CustomerForm(this);
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
Label tancore = new Label();
filterText.setPlaceholder("Meno ...");
//filterText.addValueChangeListener(e -> updateList());
//filterText.setValueChangeMode(ValueChangeMode.LAZY);
Button clearFilterTextBtn = new Button(FontAwesome.TIMES);
clearFilterTextBtn.setDescription("Clear the current name");
clearFilterTextBtn.addClickListener(e -> filterText.clear());
tancore.setCaption("TanCore s.r.o");
CssLayout filtering = new CssLayout();
filtering.addComponents(filterText, clearFilterTextBtn);
filtering.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
Button addCustomerBtn = new Button("Pridaj zamestnanca");
Button downloadXlsBtn = new Button("Stiahnuť ako .xls");
Button loginBtn = new Button("Prihlásiť sa");
// Button addEmplBtn = new Button("Pridaj");
Button backBtn = new Button("Vlož");
downloadXlsBtn.setVisible(false);
TextField name = new TextField();
PasswordField pass = new PasswordField();
// addEmplBtn.setVisible(false);
addCustomerBtn.setVisible(false);
backBtn.setVisible(false);
filtering.setVisible(false);
clearFilterTextBtn.setVisible(false);
filterText.setVisible(false);
addCustomerBtn.setStyleName(ValoTheme.BUTTON_PRIMARY);
//.setStyleName(ValoTheme.BUTTON_PRIMARY);
addCustomerBtn.setClickShortcut(KeyCode.ENTER);
backBtn.addClickListener(e -> {
//Here i want include the new data after click on the button
//grid.addColumn(filterText.getValue()); -> That it's not good, because after click the Java will Warning you
addCustomerBtn.setVisible(true);
backBtn.setVisible(false);
filtering.setVisible(false);
clearFilterTextBtn.setVisible(false);
filterText.setVisible(false);
});
addCustomerBtn.addClickListener(e -> {
addCustomerBtn.setVisible(false);
filtering.setVisible(true);
backBtn.setVisible(true);
clearFilterTextBtn.setVisible(true);
filterText.setVisible(true);
//addEmplBtn.setEnabled(true);
});
loginBtn.addClickListener(e -> {
if(name.getValue().equals("admin"))
{
if(pass.getValue().equals("admin"))
{
name.setVisible(false);
pass.setVisible(false);
loginBtn.setVisible(false);
addCustomerBtn.setVisible(true);
downloadXlsBtn.setVisible(true);
}
}
});
pass.setPlaceholder("Heslo ...");
name.setPlaceholder("Meno ...");
HorizontalLayout toolbar = new HorizontalLayout(name, pass, loginBtn,filtering, addCustomerBtn,backBtn,downloadXlsBtn);
// grid.setSelectionMode(SelectionMode.MULTI);
grid.setColumns("datum", "lastName","email","status");
// grid.setStyleName(ValoTheme.BUTTON_PRIMARY);
/*HeaderRow extraHeader = grid.prependHeaderRow();
HeaderCell joinedCell = extraHeader.join("datum", "lastName");
joinedCell.setText("Joined cell");*/
HorizontalLayout main = new HorizontalLayout(grid);
main.setSizeFull();
grid.setSizeFull();
// main.setExpandRatio(grid, 1);
grid.getColumn("datum").setWidth(100);
// grid.getColumn("datum").set
// grid.getColumn("datum").set
grid.getColumn("datum").setCaption("Dátum");
grid.getColumn("lastName").setCaption("Adam");
layout.addComponents(toolbar, main);
// fetch list of Customers from service and assign it to Grid
updateList();
setContent(layout);
// form.setVisible(false);
grid.asSingleSelect().addValueChangeListener(event -> {
//if (event.getValue() == null) {
// form.setVisible(false);
//} else {
// form.setCustomer(event.getValue());
//}
});
}
public void updateList() {
List<Customer> customers = service.findAll(filterText.getValue());
grid.setItems(customers);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}
This is clas CustomerForm.java
package my.vaadin.app;
import com.vaadin.data.Binder;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.Button;
import com.vaadin.ui.DateField;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.TextField;
import com.vaadin.ui.themes.ValoTheme;
public class CustomerForm extends FormLayout {
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField email = new TextField("Email");
private NativeSelect<CustomerStatus> status = new NativeSelect<>("Status");
private DateField birthdate = new DateField("Birthday");
private Button save = new Button("Save");
private Button delete = new Button("Delete");
private CustomerService service = CustomerService.getInstance();
private Customer customer;
private MyUI myUI;
private Binder<Customer> binder = new Binder<>(Customer.class);
public CustomerForm(MyUI myUI) {
this.myUI = myUI;
setSizeUndefined();
HorizontalLayout buttons = new HorizontalLayout(save, delete);
addComponents(firstName, lastName, email, status, birthdate, buttons);
status.setItems(CustomerStatus.values());
save.setStyleName(ValoTheme.BUTTON_PRIMARY);
save.setClickShortcut(KeyCode.ENTER);
binder.bindInstanceFields(this);
save.addClickListener(e -> this.save());
delete.addClickListener(e -> this.delete());
}
public void setCustomer(Customer customer) {
this.customer = customer;
binder.setBean(customer);
// Show delete button for only customers already in the database
delete.setVisible(customer.isPersisted());
setVisible(true);
firstName.selectAll();
}
private void delete() {
service.delete(customer);
myUI.updateList();
setVisible(false);
}
private void save() {
service.save(customer);
myUI.updateList();
setVisible(false);
}
}
This is clas CustomerService.java
package my.vaadin.app;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An in memory dummy "database" for the example purposes. In a typical Java app
* this class would be replaced by e.g. EJB or a Spring based service class.
* <p>
* In demos/tutorials/examples, get a reference to this service class with
* {#link CustomerService#getInstance()}.
*/
public class CustomerService {
private static CustomerService instance;
private static final Logger LOGGER = Logger.getLogger(CustomerService.class.getName());
private final HashMap<Long, Customer> contacts = new HashMap<>();
private long nextId = 0;
private CustomerService() {
}
/**
* #return a reference to an example facade for Customer objects.
*/
public static CustomerService getInstance() {
if (instance == null) {
instance = new CustomerService();
instance.ensureTestData();
}
return instance;
}
/**
* #return all available Customer objects.
*/
public synchronized List<Customer> findAll() {
return findAll(null);
}
/**
* Finds all Customer's that match given filter.
*
* #param stringFilter
* filter that returned objects should match or null/empty string
* if all objects should be returned.
* #return list a Customer objects
*/
public synchronized List<Customer> findAll(String stringFilter) {
ArrayList<Customer> arrayList = new ArrayList<>();
for (Customer contact : contacts.values()) {
try {
boolean passesFilter = (stringFilter == null || stringFilter.isEmpty())
|| contact.toString().toLowerCase().contains(stringFilter.toLowerCase());
if (passesFilter) {
arrayList.add(contact.clone());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
}
}
Collections.sort(arrayList, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return (int) (o2.getId() - o1.getId());
}
});
return arrayList;
}
/**
* Finds all Customer's that match given filter and limits the resultset.
*
* #param stringFilter
* filter that returned objects should match or null/empty string
* if all objects should be returned.
* #param start
* the index of first result
* #param maxresults
* maximum result count
* #return list a Customer objects
*/
public synchronized List<Customer> findAll(String stringFilter, int start, int maxresults) {
ArrayList<Customer> arrayList = new ArrayList<>();
for (Customer contact : contacts.values()) {
try {
boolean passesFilter = (stringFilter == null || stringFilter.isEmpty())
|| contact.toString().toLowerCase().contains(stringFilter.toLowerCase());
if (passesFilter) {
arrayList.add(contact.clone());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
}
}
Collections.sort(arrayList, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return (int) (o2.getId() - o1.getId());
}
});
int end = start + maxresults;
if (end > arrayList.size()) {
end = arrayList.size();
}
return arrayList.subList(start, end);
}
/**
* #return the amount of all customers in the system
*/
public synchronized long count() {
return contacts.size();
}
/**
* Deletes a customer from a system
*
* #param value
* the Customer to be deleted
*/
public synchronized void delete(Customer value) {
contacts.remove(value.getId());
}
/**
* Persists or updates customer in the system. Also assigns an identifier
* for new Customer instances.
*
* #param entry
*/
public synchronized void save(Customer entry) {
if (entry == null) {
LOGGER.log(Level.SEVERE,
"Customer is null. Are you sure you have connected your form to the application as described in tutorial chapter 7?");
return;
}
if (entry.getId() == null) {
entry.setId(nextId++);
}
try {
entry = (Customer) entry.clone();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
contacts.put(entry.getId(), entry);
}
/**
* Sample data generation
*/
public void ensureTestData() {
if (findAll().isEmpty()) {
for (int i = 31; i > 0; i--) {
Customer c = new Customer();
c.setDatum(i+".7");
save(c);
}
}
}
}
I want have this in my WebApp
This is actualy my WebApp
Ok so heres the thing I am working with an api that for one JSON parameter can return two different types. So I can receive from the server either a JSON Object or a String. I'm pretty new to Android development so if someone could explain to me with maybe a code example how I can handle that problem.
Example json responses {video:"ID OF VIDEO"} or {video:{id:"ID OF VIDEO",...extra data}}. I had a look at custom deserialisers but can't find an example that is easy to follow. There must be a simple way of solving my problem. Currently I receive error "Expected string but found BEGIN OBJECT"
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MyNotification {
#SerializedName("_id")
#Expose
private String Id;
#SerializedName("comment")
#Expose
private String comment;
#SerializedName("createdAt")
#Expose
private String createdAt;
#SerializedName("message")
#Expose
private String message;
#SerializedName("read")
#Expose
private Boolean read;
#SerializedName("recipient")
#Expose
private String recipient;
#SerializedName("sender")
#Expose
private User sender;
#SerializedName("type")
#Expose
private String type;
// #SerializedName("video")
// #Expose
// private String video;
/**
*
* #return
* The Id
*/
public String getId() {
return Id;
}
/**
*
* #param Id
* The _id
*/
public void setId(String Id) {
this.Id = Id;
}
/**
*
* #return
* The comment
*/
public String getComment() {
return comment;
}
/**
*
* #param comment
* The comment
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
*
* #return
* The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
*
* #param createdAt
* The createdAt
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
*
* #return
* The message
*/
public String getMessage() {
return message;
}
/**
*
* #param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}
/**
*
* #return
* The read
*/
public Boolean getRead() {
return read;
}
/**
*
* #param read
* The read
*/
public void setRead(Boolean read) {
this.read = read;
}
/**
*
* #return
* The recipient
*/
public String getRecipient() {
return recipient;
}
/**
*
* #param recipient
* The recipient
*/
public void setRecipient(String recipient) {
this.recipient = recipient;
}
/**
*
* #return
* The sender
*/
public User getSender() {
return sender;
}
/**
*
* #param sender
* The sender
*/
public void setSender(User sender) {
this.sender = sender;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
// /**
// *
// * #return
// * The video
// */
// public String getVideo() {
// return video;
// }
//
// /**
// *
// * #param video
// * The video
// */
// public void setVideo(String video) {
// this.video = video;
// }
}
and the part that craps out
Gson gson = new Gson();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<MyNotification>>(){}.getType();
notficationsList = (List<MyNotification>) gson.fromJson(jsonString, listType);
Sorry it took so long:
Your best bet is to repair the JSON, if you must map it to an Object.
Try cleaning the JSON with this code:
public static String cleanJson(String json) {
int videoPos = json.indexOf("video");
if(videoPos == -1) {
return json; //return, no video here
}
boolean isObject = false;
int objectBegin = -1;
String cleanedJson = json.replaceAll("\\\"", "\\\\");
for(int i = videoPos; i < cleanedJson.length(); i++) {
if(cleanedJson.charAt(i) == '"') {
System.out.println("string");
return json; // its a string anyway
}
if(cleanedJson.charAt(i) == '{') {
//its an object
// i now is the position beginning the object
objectBegin = i;
}
} //replace " with space
if(objectBegin == -1) {// we did not find any { or " it is a string
return json;
}
boolean inString = false;
int objectEnd = -1;
for(int i = objectBegin; i < cleanedJson.length(); i++) {
//looking for the end of the object;
if(cleanedJson.charAt(i) == '"') inString = !inString;
if(cleanedJson.charAt(i) == '}') {
objectEnd = i;
break;
}
}
if(objectEnd != -1) {
String start = json.substring(0,objectBegin);
String videoPart = json.substring(objectBegin, objectEnd+1);
String end = json.substring(objectEnd+1);
// now we want to get the id
String newVideoPart = "";
int idStart = videoPart.indexOf("id");
int idStringStart = -1;
int idStringEnd = -1;
for(int i = idStart; i < videoPart.length(); i++) {
if(videoPart.charAt(i) == '"') {
if(idStringStart == -1) {
idStringStart = i;
} else {
idStringEnd = i;
break;
}
}
}
if(idStringStart != -1 && idStringEnd != -1) {
newVideoPart = videoPart.substring(idStringStart, idStringEnd+1);
}
return start+newVideoPart+end;
}
return json;
}
Works with these two test jsons:
System.out.println(cleanJson("{video:\"1234\"}"));
System.out.println(cleanJson("{video:{id:\"2345\", name=\"test\"}}"));
Try it like this:
notficationsList = (List<MyNotification>) gson.fromJson(cleanJson(jsonString), listType);
Ok so the solution I went with I wrote my own type adapter that gson allow you to use
public class Helper_StringAdapter extends TypeAdapter<String>{
#Override
public String read(com.google.gson.stream.JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL){
in.nextNull();
return null;
}else if(in.peek() == JsonToken.BEGIN_OBJECT && in.getPath().contains(".video")){
L.e("VIDEO IS AN OBJECT!");
String userId = readAndReturnVideoId(in);
return userId;
}else{
return in.nextString();
}
}
private String readAndReturnVideoId(com.google.gson.stream.JsonReader reader) throws IOException{
String id = "";
reader.beginObject();
while(reader.hasNext()){
String name = reader.nextName();
if(name.equals("_id")){
id = reader.nextString();
}else{
reader.skipValue();
}
}
reader.endObject();
L.e("READ ID RETURNED"+id);
return id;
}
#Override
public void write(com.google.gson.stream.JsonWriter out, String value) throws IOException {
L.e("TEST "+out);
}
}
Then in my activity data manager (Recyclerview Adapter)
public void updateData (JSONArray dataset) {
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(String.class,new Helper_StringAdapter());
Gson gson = gsonb.create();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<FrameNotification>>(){}.getType();
notficationsList = (List<FrameNotification>) gson.fromJson(jsonString, listType);
}
Seems to do the job
Sorry if the title wasn't very clear.
anyways, I'm making a monopoly game and im currently working on the income tax space. I have an idea of how to make that, but what I'm stuck on is a method that is supposed to get the total value of all money, properties, etc.
Here's what i have so far:
public int getTotVal()
{
int tot = 0;
for (int i = 0; i < this.properties.size(); i++)
tot += this.properties.get(i).mortgage;
return tot;
}
The for loop is supposed to run through the ArrayList of properties, and for each property, add the mortgage value to the varialble "tot".
I know this isn't right, but how would i do it correctly?
EDIT
Player:
import java.util.ArrayList;
public class Player
{
private String name;
private String token;
public int wallet;
private ArrayList properties;
public Player(String name, String token, int wallet, Property prop)
{
this.name = name;
this.token = token;
this.wallet = wallet;
this.properties.add(prop);
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the token
*/
public String getToken() {
return token;
}
/**
* #param token the token to set
*/
public void setToken(String token) {
this.token = token;
}
/**
* #return the wallet
*/
public int getWallet() {
return wallet;
}
/**
* #param wallet the wallet to set
*/
public void setWallet(int wallet) {
this.wallet = wallet;
}
/**
* #return the properties
*/
public ArrayList getProperties() {
return properties;
}
/**
* #param properties the properties to set
*/
public void setProperties(ArrayList properties) {
this.properties = properties;
}
//add buy()
//add butProp()
//add pay()
//add payRent()
public void pay(int amount)
{
this.wallet -= amount;
}
public int getTotVal()
{
int tot = 0;
for (Property property : this.properties)
{
tot += property.mortgage;
}
return tot;
}
}
Property:
package monopolysrc;
import java.util.Scanner;
public class Property extends Space
{
private int value;
private boolean owned;
private int mortgage;
public Property(String fn,String ln, int val, int mortgage, boolean owned)
{
super(fn,ln);
val = value;
owned = false;
this.mortgage = mortgage;
}
/**
* #return the value
*/
public int getValue() {
return value;
}
/**
* #param value the value to set
*/
public void setValue(int value) {
this.value = value;
}
/**
* #return the owned
*/
public boolean isOwned() {
return owned;
}
/**
* #param owned the owned to set
*/
public void setOwned(boolean owned) {
this.owned = owned;
}
/**
* #return the mortgage
*/
public int getMortgage() {
return mortgage;
}
/**
* #param mortgage the mortgage to set
*/
public void setMortgage(int mortgage) {
this.mortgage = mortgage;
}
}
Try this:
public int getTotVal() {
int tot = 0;
for (int i = 0; i < this.properties.size(); i++)
tot += this.properties.get(i).mortgage;
return tot;
}
There's a neat way to loop over every element of a List:
for (Property property : this.properties) {
tot += property.mortgage;
}
I am sure this is something stupid, but I can't figure it out for the life of me.... In the main method, when I am trying to create new artists, I keep getting an error on the creating a new "Recording" line (ie: surfacing and pop). It is saying it requires String, String[] but is getting String, MusicCollection.Artist. And it says "actual argument MusicCollection.Artist cannot be converted to String[] by method invocation conversion.
public class MusicCollection {
private Artist[] artists = new Artist[100];
private Recording[] recordings = new Recording[200];
private int artistCount = 0;
private int recordingCount = 0;
//toString method for MusicCollection
public String toString() {
StringBuffer sb = new StringBuffer();
if (recordingCount > 0) {
sb.append(recordings[0].toString());
for (int i = 1; i < recordingCount; i++) {
sb.append("\n" + recordings[i]);
}
}
return sb.toString();
}
public class Artist {
private String name;
/**
* Construct an artist object and add it to the collection.
*
* #param name the name of the Artist
*/
public Artist(String name) {
this.name = name;
artists[artistCount++] = this;
}
/**
* Retrieve the artist as a string
*
* #return the string representation of the artist
*/
public String toString() {
return name;
}
}
public class Recording {
private String name;
private Artist[] artists = new Artist[100];
private Track[] tracks = new Track[200];
private int trackCount = 0;
public class Track {
private String name;
/**
* Construct track object and add it to the collection.
*
* #param name the name of the track
*/
public Track(String name) {
this.name = name;
tracks[trackCount++] = this;
}
/**
* Retrieve the track as a string
*
* #return the string representation of the track
*/
public String toString() {
return name;
}
}
public Recording(String name, String Artist[]) {
this.name = name;
this.artists = artists;
recordings[recordingCount++] = this;
}
public String toString() {
StringBuffer sb = new StringBuffer(name);
sb.append(" by " + artists + ": ");
if (trackCount > 0) {
sb.append(tracks[0].toString());
for (int i = 1; i < trackCount; i++) {
sb.append(", " + tracks[i]);
}
}
return sb.toString();
}
}
public static void main(String[] args) {
MusicCollection mc = new MusicCollection();
Artist sarahM = mc.new Artist("Sarah McLachlan");
Recording surfacing = mc.new Recording("Surfacing", sarahM);
Recording.Track surfacing1 = surfacing.new Track("Building a Mystery");
Recording.Track surfacing4 = surfacing.new Track("Adia");
Artist u2 = mc.new Artist("U2");
Recording pop = mc.new Recording("Pop", u2);
Recording.Track pop1 = pop.new Track("Discotheque");
Recording.Track pop5 = pop.new Track("Miami");
System.out.println(mc);
}
}
Needed to have:
public Recording(String name, Artist someArtist)
and in my Recording class, only have:
private Artist artist;
since I had already declared Artist as an array.
I also had to change this.artists = artists; to this.artists = someArtist;, since that was the variable I am passing. Worked like a charm after!
I am using Hibernate (and new at it also) and trying to use an aggregate function to retrieve count value and additional fields from a MS SQL database. I have created a POJO class for the data as follows:
package com.hdl.model.db;
import java.util.Date;
#Entity
#Table(name = "sfdc_stg_lab_orders")
#SqlResultSetMappings( {
SqlResultSetMapping(name = "ProfessorAndManager",
columns = { #ColumnResult(name = "total"),
#ColumnResult(name = "org_name"),
#ColumnResult(name = "drawMonth"),
#ColumnResult(name = "drawYear")
})
})
public class OrgnameByMonthYear {
public OrgnameByMonthYear(Id sfdc_stg_lab_order_key, String org_name,int drawMonth,
int drawYear , Double total){
this.org_name = org_name;
this.total = total;
this.drawMonth = drawMonth;
this.drawYear = drawYear;
}
#Id
#GeneratedValue
#Column(name= "sfdc_stg_lab_order_key")
/*
* Unique ID - System Generated
*/
private Integer sfdc_stg_lab_order_key;
/*
* Name of the Organization
*/
#Column(name= "org_name")
private String org_name;
#Column(name = "total")
private double total;
#Column(name = "drawMonth")
private int drawMonth;
#Column(name = "drawYear")
private int drawYear;
public Integer getSfdc_stg_lab_order_key() {
return sfdc_stg_lab_order_key;
}
public void setSfdc_stg_lab_order_key(Integer sfdc_stg_lab_order_key) {
this.sfdc_stg_lab_order_key = sfdc_stg_lab_order_key;
}
/**
* #return the orgname
*/
public String getOrg_name() {
return org_name;
}
/**
* #param orgname to set
*/
public void setOrg_name(String org_name) {
this.org_name = org_name;
}
/**
* #return the year
*/
public double getTotal() {
return total;
}
/**
* #param total to set
*/
public void setTotal(long total) {
this.total = total;
}
/**
* #return the month
*/
public int getDrawMonth() {
return drawMonth;
}
/**
* #param month to set
*/
public void setDrawMonth(int drawMonth) {
this.drawMonth = drawMonth;
}
/**
* #return the year
*/
public int getDrawYear() {
return drawYear;
}
/**
* #param year to set
*/
public void setDrawYear(int drawYear) {
this.drawYear = drawYear;
}
#Override
public String toString() {
return "sfdc_stg_lab_orders [sfdc_stg_lab_order_key=" +
sfdc_stg_lab_order_key + "total=" + total + ", org_name=" + org_name + "]";
}
}
I am calling the following to retrieve the data using Hibernate find:
#SuppressWarnings("unchecked")
#Override
public List<OrgnameByMonthYear> getOrgnameByMonthYear() {
logger.info("Retrieving getOrgnameByMonthYear list inside SfdcStgLabOrdersDAOImpl ....");
return hibernateTemplate.find("select count(org_name) AS total, org_name,
month(specimen_draw_date_1) AS drawMonth, year(specimen_draw_date_1) AS drawYear from
OrgnameByMonthYear group by org_name, month(specimen_draw_date_1),
year(specimen_draw_date_1)");
}
I am getting the following error in Java "Unable to cast to OrgnameByMonthYear class". Thanks in advance for any assistance!
org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'executeFirstTask' on target class [class com.hdl.service.impl.SchedulerService] failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.hdl.model.db.OrgnameByMonthYear at
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:320) at
org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113)
at org.quartz.core.JobRunShell.run(JobRunShell.java:223)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.hdl.model.db.OrgnameByMonthYear
This can be done by creating a new class AggregationResults that contains the results of the query:
public class AggregationResults {
private Integer total;
private String orgName;
private Integer drawMonth;
private Integer drawYear;
... constructor with all properties here ...
}
And then rewrite the query so that it returns AggregationResults using the new operator:
#SuppressWarnings("unchecked")
#Override
public List<AggregationResults> getOrgnameByMonthYear() {
logger.info("Retrieving AggregationResults list inside SfdcStgLabOrdersDAOImpl ....");
return hibernateTemplate.find("select new com.your.package.AggregationResults( count(org_name) AS total, org_name,
month(specimen_draw_date_1) AS drawMonth, year(specimen_draw_date_1) AS drawYear) from
OrgnameByMonthYear group by org_name, month(specimen_draw_date_1),
year(specimen_draw_date_1)");
}