How to invoke ParkingTicket(parker, parkee)? - java

Here is my problem I can't seem to figure out how to invoke a ParkingTicket object if (carMinutesPaid>meterMinutesPaid)? can any one help here are the details below to the question.
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
System.out.println("null");
}
return new ParkingTicket(parker, parkee);
}
Here is the question for my project.
Remember, this method must be able to be used without a ParkingTicket object in existence.
Using a Car parameter and a ParkingMeter parameter, decide whether a ParkingTicket object should be created.
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and return the result.
Return null if a ticket was not merited.
Here is my car class:
/**
* This is a Car class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class Car
{
private static final int MINIMUM_PLATE_LENGTH=2;
private static final int MAXIMUM_PLATE_LENGTH=7;
public static final char MANUAL_TRANSMISSION='m';
public static final char AUTOMATIC_TRANSMISSION='a';
private static int defaultMinutesParked = 0;
private static double defaultOdometerInKm = 50000.5;
private String licensePlate;
private char transmissionType;
private double odometerInKm;
private int minutesParked;
/**
* #param newProposedLicensePlate the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public Car(String newProposedLicensePlate)
{
setLicensePlate(newProposedLicensePlate);
transmissionType = AUTOMATIC_TRANSMISSION;
odometerInKm = defaultOdometerInKm;
minutesParked = defaultMinutesParked;
}
/**
* #return the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public String getLicensePlate()
{
return licensePlate;
}
/**
* #return the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
*/
public char getTransmissionType()
{
return transmissionType;
}
/**
* #return the odometer in kilometers
*/
public double getOdometerInKm()
{
return odometerInKm;
}
/**
* Recieve the license plate
* Mutator.licensePlate.
* #param proposedLicense String Conforming to ICBC *length* guidlines:
* http://www.icbc.com/vehicle-registration/license-plates/Pages/Personalized-licence-plates.aspx
* May also be null. The null represents a car without a plate
* If validation fails, null will be set.
*/
public void setLicensePlate(String proposedLicense)
{
if(proposedLicense==null){
licensePlate = proposedLicense;
}
else if(proposedLicense.length()>=MINIMUM_PLATE_LENGTH && proposedLicense.length()<=MAXIMUM_PLATE_LENGTH){
licensePlate = proposedLicense;
}
else{
licensePlate = null;
}
}
/**
* #param mOrA recieve the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
* if invalid type of transmission is entered then will return "Installation failure: 'mOrA' is not a vaild transmission type"
*/
public void setTransmissionType(char mOrA)
{
if(mOrA==MANUAL_TRANSMISSION){
transmissionType = mOrA;
}
else if(mOrA==AUTOMATIC_TRANSMISSION){
transmissionType = mOrA;
}
else if (mOrA==mOrA){
System.out.println("Installation failure:" + " " + ("'")+(mOrA)+("'") + " " + "is not a valid transmission type.");
}
else{
transmissionType = mOrA;
}
}
/**
* #return the value of the odometer in with the String kilometers
*/
public String readOdometer()
{
return odometerInKm + " " + "kilometers";
}
/**
* #return the false if the minutesParked equals zero; otherwise true
*/
public boolean isParked()
{
if(minutesParked==defaultMinutesParked){
return false;
}
else{
return true;
}
}
/**
* #param duration replaces any existing value in minutesParked with the value from duration
*/
public void park(int duration)
{
if(duration>=defaultMinutesParked){
minutesParked = duration;
}
}
/**
* #param aOdometerInKm recieve the odometer in kilometers
*/
public void setOdometerInKm(double aOdometerInKm)
{
odometerInKm = aOdometerInKm;
}
/**
* #param aMinutesParked recieve the minutes parked in the stall but can not be a negative number
* if invalid number of minutes is entered then the number of minutes will not change.
*/
public void setMinutesParked(int aMinutesParked)
{
if(aMinutesParked>=defaultMinutesParked){
minutesParked = aMinutesParked;
}
else{
return;
}
}
/**
* #return the minutes parked
*/
public int getMinutesParked()
{
return minutesParked;
}
}
here is my ParkingMeter class:
/**
* This is a ParkingMeter class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class ParkingMeter
{
private int minutesPaid;
private String methodPaid;
/**
* #param newMinutesPaid the minutes paid for parking meter
*/
public ParkingMeter()
{
}
/**
* #return the minutes paid
*/
public int getMinutesPaid()
{
return minutesPaid;
}
/**
* #return the method paid
*/
public String getMethodPaid()
{
return methodPaid;
}
/**
* #param paidBy the payment method customer will paid by
*/
public void setMethodPaid(String paidBy) /* BONUS for creating method paid */
{
if(methodPaid=="Visa"){
methodPaid = paidBy;
}
else if(methodPaid=="Master Card"){
methodPaid = paidBy;
}
else if(methodPaid=="American Express"){
methodPaid = paidBy;
}
else if(methodPaid=="Cash"){
methodPaid = paidBy;
}
else if(methodPaid=="Debit"){
methodPaid = paidBy;
}
else{
methodPaid = paidBy;
}
}
/**
* #param quantity the added minutes paid must not have a negative number
*/
public void addMinutesPaid(int quantity)
{
if(quantity>=0){
minutesPaid+=quantity;
}
}
}
and here is my ParkingTicket class:
/**
* This is a ParkingTicket class for Impark.
*
* #author Tre
* #version 1.0
*/
public class ParkingTicket
{
private final String referenceNumber;
private static String carLicensePlate;
private static int carMinutesParked;
private static int meterMinutesPaid;
private static int count = 1000;
private static String PREFIX = "V";
/**
* #param recorededLicense the value of the tick number
*/
private ParkingTicket(String recordedLicense, int newCarMinutesParked, int newMeterPaidMinutes)
{
referenceNumber = (PREFIX+count++);
carMinutesParked = newCarMinutesParked;
meterMinutesPaid = newMeterPaidMinutes;
}
/**
* #param
*/
private ParkingTicket(Car parker, ParkingMeter parkee)
{
this(parker.getLicensePlate(), parker.getMinutesParked(), parkee.getMinutesPaid());
}
/**
* #return referenceNumber the reference number
*/
public String getReferenceNumber()
{
return referenceNumber;
}
/**
* #return carLicensePlate the car's license plate
*/
public String getCarLicensePlate()
{
return carLicensePlate;
}
/**
* #return carMinutesParked the minutes car was parked
*/
public int getCarMinutesParked()
{
return carMinutesParked;
}
/**
* #return meterMinutesPaid the minutes paid on meter
*/
public int getMeterMinutesPaid()
{
return meterMinutesPaid;
}
/**
* #return count the with initial value of 1000
*/
public int getCount()
{
return count;
}
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
return null;
}
return new ParkingTicket(parker, parkee);
}
}

This requirement:
Using a Car parameter and a ParkingMeter parameter, decide whether a
ParkingTicket object should be created.
suggests that you provide two parameters to the checkParking method, one is of the type Car and one of the ParkingMeter. So it should be like so:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
This code :
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
won't even compile
line 1: you're trying to assign int to object - that's called type mismatch.
line 2: variable parkee is not declared anywhere (except for the headline of the question).
You see, only the Car object holds the information about the parking duration, and you need the object for creating parking ticket. Same for the ParkingMeter
It should be vice versa - you get the values from the objects:
int carMinutesParked = car.getMinutesParked();
int meterMinutesPaid = meter.getMinutesPaid();
and proceed from here with if( or even use it in if without declaring temporary variables).
This one:
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and
return the result.
you did OK.
Now this requirement:
Return null if a ticket was not merited.
suggest the method will return null, not string that equals to "null" .
So, based on these requirements it should rather be:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
{
//sanity check (bonus)
if ((car == null) || (meter == null))
return null;
if(car.getMinutesParked() > meter.getMinutesPaid()){
return new ParkingTicket(car, meter);
}
return null;
}
Note however, I don't know if you need any additional logic in this code and don't suggest this should be your final version, just explaining the general approach.

Related

Sort table columns on header click?

The code below produces this outout:
If you try this code, vaadin automatically knows how to sort on CARMAKE & TOPSPEED when you click on their headers.
PASSENGER & DRIVER are not sorted on a header click.
How can I do this?
Where does the Table say "I don't know how to sort something of type PERSON so I won't add a click listener to that header"?
I was able to extend the beamItemContainer & override the sort method. I then could add buttons to the view that sort the columns. But I want to be able to click the table headers!
I had thought I could add TableHeaderClickListeners but why doesn't vaadin already do it for me when I override the beanItemContainer's sort? It already does this for CARMAKE & TOPSPEED.
#Override
public void init(VaadinRequest request) {
BeanItemContainer<SportsCar> beans = new BeanItemContainer<SportsCar>(SportsCar.class);
Person tom = new Person("Tom");
Person dick = new Person("Dick");
Person harry = new Person("Harry");
beans.addBean(new SportsCar("ferrari",180.0,tom,dick));
beans.addBean(new SportsCar("Aston Martin",165.0,harry,null));
Table t = new Table();
t.setContainerDataSource(beans);
t.setSizeFull();
this.setContent(t);
}
public class SportsCar {
String carMake;
double topspeed;
Person driver;
Person Passenger;
public SportsCar(String carMake, double topspeed, Person driver, Person passenger) {
this.carMake = carMake;
this.topspeed = topspeed;
this.driver = driver;
this.Passenger = passenger;
}
/**
* Get the carMake.
*
* #return the carMake.
*/
public String getcarMake() {
return carMake;
}
/**
* Set the carMake.
*
* #param carMake
* the carMake.
*/
public void setcarMake(String carMake) {
this.carMake = carMake;
}
/**
* Get the topspeed.
*
* #return the topspeed.
*/
public double getTopspeed() {
return topspeed;
}
/**
* Set the topspeed.
*
* #param topspeed
* the topspeed.
*/
public void setTopspeed(double topspeed) {
this.topspeed = topspeed;
}
/**
* Get the driver.
*
* #return the driver.
*/
public Person getDriver() {
return driver;
}
/**
* Set the driver.
*
* #param driver
* the driver.
*/
public void setDriver(Person driver) {
this.driver = driver;
}
/**
* Get the passenger.
*
* #return the passenger.
*/
public Person getPassenger() {
return Passenger;
}
/**
* Set the passenger.
*
* #param passenger
* the passenger.
*/
public void setPassenger(Person passenger) {
Passenger = passenger;
}
}
public class Person {
String carMake;
/**
* Create a Demo.Person.
*/
public Person(String carMake) {
this.carMake = carMake;
}
/**
* Get the carMake.
*
* #return the carMake.
*/
public String getcarMake() {
return carMake;
}
/**
* Set the carMake.
*
* #param carMake
* the carMake.
*/
public void setcarMake(String carMake) {
this.carMake = carMake;
}
#Override
public String toString(){
return carMake;
}
}
Java does not know how to compare objects per se. First you have to specify, that these objects can be compared by implementing the interface "Comparable". Then you need to override the compareTo method like so:
public int compareTo(Person p) {
return getcarMake().compareTo(p.getcarMake());
}
this should do the trick (I did not test it though).

Bank Simulator - doBusiness method help LinkedList/Queue

So I have to create a Bank Simulator project for class, and so far I have a few of the methods implemnted. But currently I am having trouble with the doBusiness method in the ServiceCenter class. Here is the code I have so far.
Main: BankSimulator
import java.util.Scanner;
public class BankSimulator {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("What is the time duration (in minutes) to be simulated? ");
int maxTime = input.nextInt();
System.out.print("What percentage of the time (0-100) does a customer arrive? ");
int arrivalProb = input.nextInt();
ServiceCenter bank = new ServiceCenter();
while (bank.getTime() <= maxTime || bank.customersRemaining()) {
if (bank.getTime() <= maxTime && customerArrived(arrivalProb)) {
bank.addCustomer();
}
bank.doBusiness();
}
//bank.displayStats();
}
private static boolean customerArrived(int prob)
{
return (Math.random()*100 <= prob);
}
}
Server class:
public class Server {
private static int nextID = 1;
private int serverID;
private int endTime;
private Customer serving;
public Server()
{
serverID = nextID;
nextID++;
endTime = 0;
serving = null;
}
/**
* Accessor method for getting the server ID number.
* #return the server ID
*/
public int getID()
{
return serverID;
}
/**
* Assigns a customer to the server and begins the transaction.
* #param c the new customer to be served
* #param time the time at which the transaction begins
*/
public void startCustomer(Customer c, int time)
{
serving = c;
endTime = time + c.getJobLength();
}
/**
* Accessor method for getting the current customer.
* #return the current customer, or null if no customer
*/
public Customer getCustomer()
{
return serving;
}
/**
* Identifies the time at which the server will finish with
* the current customer
* #return time at which transaction will finish, or 0 if no customer
*/
public int busyUntil()
{
return endTime;
}
/**
* Finishes with the current customer and resets the time to completion.
*/
public void finishCustomer()
{
serving = null;
endTime = 0;
}
}
Customer class:
import java.util.Random;
public class Customer {
private static final int MAX_LENGTH = 8;
private static final Random rand = new Random();
private static int nextID = 1;
private int customerID;
private int arrivalTime;
private int jobLength;
/**
* Constructs a customer with the next available ID number,
* the specified arrival time, and a random job length.
* #param arrTime the time at which the customer arrives
*/
public Customer(int arrTime)
{
customerID = nextID;
nextID++;
arrivalTime = arrTime;
jobLength = rand.nextInt(MAX_LENGTH)+1;
}
/**
* Accessor method for getting the customer's ID number.
* #return the customer ID
*/
public int getID()
{
return customerID;
}
/**
* Accessor method for getting the customer's arrival time.
* #return the time at which the customer arrived
*/
public int getArrivalTime()
{
return arrivalTime;
}
/**
* Accessor method for getting the length of the job
* #return the job length (in minutes)
*/
public int getJobLength()
{
return jobLength;
}
}
I had to create the following class called ServiceCenter where getTime returns the time in the simulation which starts at 0 and increments on each step. An addCustomer method where we add a customer to the queue and displayed a message. A customerRemaining which returns true if a customer is currently being waited on. Lastly the doBusiness method which increments the time, if the server finished with a customer remove them from the queue, and if the server is free and there is a customer in the queue, begin serving them. I have the first few ones done except the doBusiness method I am stuck on. Does anyone have any tips?
The code listed above was created by Dave Reed and I take no credit for the code.
ServiceCenter class:
import java.util.LinkedList;
import java.util.Queue;
public class ServiceCenter {
private int arrivalTime, departureTime;
private Queue <Customer> customer;
private Server server;
public ServiceCenter()
{
server = new Server();
customer = new LinkedList <Customer> ();
}
public String addCustomer ()
{
Customer customer1 = new Customer (arrivalTime);
customer.add(customer1);
String result = "" + customer1.getArrivalTime() + "" + customer1.getID() + "" + customer1.getJobLength();
return result;
}
public void doBusiness()
{
if(!customer.isEmpty())
{
if(server == null)
{
customer.remove();
}
}
}
public int getTime()
{
return departureTime - arrivalTime;
}
public boolean customersRemaining()
{
if (!(customer.isEmpty()))
return true;
else
return false;
}
}
Any help at all or tips would be greatly appreciated. I've been trying to figure it out for a week now, but for some reason queues are my weakness. Thanks for reading and sorry for it being so long. Just wanted it to be detailed.
You are using new Customer (arrivalTime); but you don't have the arrivalTime in your constructor of the ServiceCenter-class.

GWT RPC Deferred Binding Failed

We are co-developing a GWT web app that already has working RPC calls for other modules. We built a new RPC module (based on the existing architecture) that compiles and runs, but fails throwing a run-time exception on the following line:
this.dashboardService = GWT.create(DashboardService.class);
The last line in the console is "Uncaught exception escaped" followed by the stack trace to the GWT.create() line above, which is preceded by the console error message:
Deferred binding failed for ... expect subsequent failures [ERROR]
Before those two lines is a laundry list of red errors that begins as follows:
[INFO] [(...)] - Module ... has been loaded
[DEBUG] [(...)] - Rebinding (...).DashboardService
[DEBUG] [(...)] - Invoking generator com.google.gwt.user.rebind.rpc.ServiceInterfaceProxyGenerator
[DEBUG] [(...)] - Generating client proxy for remote service interface '(...).DashboardService'
[INFO] [(...)] - Checking type argument 0 of type 'java.util.Arrays.ArrayList' because it is exposed as an array with a maximum dimension of 1 in this type or one of its subtypes (reached via (...).DashboardChannelSummary)
.
.
.
(more errors without stack trace or line numbers)
The console asks "Did you forget to inherit a module?" but based upon my research, this is not the problem; the problem is somewhere in the GWT deferred binding process, which is not visible in the stack trace. I suspect the bolded line above to be the issue but I cannot make heads or tales of this error message without a line number. Here is the code with proprietary package /module names replaced with (...):
web.xml
<servlet>
<servlet-name>(...) DashboardService
</servlet-name>
<servlet-class>(...).server.DashboardServiceImpl
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>(...) DashboardService
</servlet-name>
<url-pattern>/(...)/DashboardService</url-pattern>
</servlet-mapping>
DashboardChannelSummary.java
/**
* This class is an in memory representation of the results of a document search
*/
public class DashboardChannelSummary implements IsSerializable {
/** Only searches for documents from the past in this amount (the past week) */
private static final int DEFAULT_DASHBOARD_HISTORY_IN_DAYS = -7;
/** array of channels */
private List<Channel> channels;
/** iterator */
private Iterator<Channel> iterator;
/** */
private final static String IMAGE_PATH = "/images/channels/";
/** */
private final static String IMAGE_EXT = ".png";
/** constant for the channel header name */
public final static String BUSINESS_LABEL = "business aviation";
/** constant for the channel header name */
public final static String COMMERCIAL_LABEL = "commercial aviation";
/** constant for the channel header name */
public final static String MRO_LABEL = "mro";
/** constant for the channel header name */
public final static String DEFENSE_LABEL = "defense";
/**
*
*/
public enum CHANNEL_NAME {
BUSINESS (BUSINESS_LABEL, DocumentSummary.BA_ID),
COMMERCIAL (COMMERCIAL_LABEL, DocumentSummary.CA_ID),
MRO (MRO_LABEL, DocumentSummary.MRO_ID),
DEFENSE (DEFENSE_LABEL, DocumentSummary.DEFENSE_ID);
/** */
public String label;
/** */
public int ID;
/** */
private CHANNEL_NAME(String label, int ID) {
this.label = label.toUpperCase();
this.ID = ID;
}
};
/**
*
*/
public static List<String> channelNames() {
ArrayList<String> channels = new ArrayList<String>(CHANNEL_NAME.values().length);
for(int i=0; i<channels.size(); i++) {
channels.add(CHANNEL_NAME.values()[i].label);
}
return channels;
}
/**
*
*/
public static int[] channelIDs() {
int[] IDs = new int[CHANNEL_NAME.values().length];
for(int i=0; i<IDs.length; i++) {
IDs[i] = CHANNEL_NAME.values()[i].ID;
}
return IDs;
}
/**
*
* #return
*/
public static int channelCount() {
return CHANNEL_NAME.values().length;
}
/**
*
*/
public static Date cutoffDate() {
Date date = new Date(0);
CalendarUtil.addDaysToDate(date, DEFAULT_DASHBOARD_HISTORY_IN_DAYS);
return date;
}
/**
*
*/
public class Channel {
/** the name of this channel */
private CHANNEL_NAME name;
/** The list of documents */
private List<DocumentSummary> docs;
/** the iterator */
private Iterator<DocumentSummary> iterator;
/**
*
*/
public Channel(List<DocumentSummary> docs, CHANNEL_NAME name) {
this.docs = docs;
this.name = name;
iterator = docs.iterator();
}
/**
*
*/
public String getLabel() {
return name.label;
}
/**
*
*/
public List<DocumentSummary> getDocuments() {
return docs;
}
/**
*
*/
public boolean hasDocuments() {
return iterator.hasNext();
}
/**
*
* #return
*/
public DocumentSummary nextDocument() {
if(iterator.hasNext()) {
return iterator.next();
}
else {
return null;
}
}
/**
*
*/
public String nextImageURL() {
return GWT.getHostPageBaseURL().concat(IMAGE_PATH + String.valueOf(Random.nextInt(channels.size()) - 1) + IMAGE_EXT);
}
}
/**
* Constructor
*/
public DashboardChannelSummary() {
channels = new ArrayList<Channel>(CHANNEL_NAME.values().length);
iterator = channels.iterator();
}
/**
* Constructor
*/
public DashboardChannelSummary(List<List<DocumentSummary>> channelList) {
channels = new ArrayList<Channel>(CHANNEL_NAME.values().length);
iterator = channels.iterator();
int count = 0;
for(List<DocumentSummary> channelData : channelList)
{
channels.add(new Channel(channelData, CHANNEL_NAME.values()[count++]));
}
}
/**
* #return
*/
public List<Channel> getChannels() {
return channels;
}
/**
* #return
*/
public Channel getChannel(int channel) {
return channels.get(channel);
}
/**
* #return
*/
public Channel nextChannel() {
if(iterator.hasNext()) {
return iterator.next();
}
else {
return null;
}
}
/**
* #return
*/
public List<DocumentSummary> getDocuments(int channel) {
return this.getChannel(channel).getDocuments();
}
}
DashboardPresenter.java:
private final DashboardServiceAsync dashboardService;
and the deferred binding that fails in the Constructor:
this.dashboardService = GWT.create(DashboardService.class);
DashboardServiceAsync.java:
public interface DashboardServiceAsync {
/**
*
* #param channelIDs
* #param startDate
* #param async
*/
void getChannelSummary(int[] channelIDs, Date startDate, AsyncCallback<DashboardChannelSummary> async);
}
DashboardService.java:
#RemoteServiceRelativePath("DashboardService") public interface DashboardService extends RemoteService {
/**
*
* #param channelIDs
* #param startDate
* #return
*/
DashboardChannelSummary getChannelSummary(int[] channelIDs, Date startDate);
}
On the server:
DashboardServiceImpl.java:
public class DashboardServiceImpl extends RemoteServiceServlet implements DashboardService {
/**
*
* #param channelIDs
* #param startDate
* #return
*/
#Override
public DashboardChannelSummary getChannelSummary(int[] channelIDs, Date startDate) {
return new DashboardDaoImpl().getChannelSummary(channelIDs, startDate);
}
}
We have double and triple checked our RPC code for accuracy based on the documentation and the suggestions on SO, such as making sure the method signatures are correct across all interfaces and implementations. Anything obviously wrong jumping out to anyone? Is there a way we can we debug this error with more detail?
UPDATE
DashboardChannelSummary.java redesigned for max efficiency in transporting the data from the server to the client, with all properties now "serializable:"
/**
* This class is an in memory representation of the results of a document search.
*/
public class DashboardChannelSummary implements IsSerializable {
/** Only searches for documents from the past in this amount (the past week) */
private static final int DEFAULT_DASHBOARD_HISTORY_IN_DAYS = -7;
/** array of channels */
private ArrayList<ArrayList<DocumentSummary>> channels;
/** */
private int channel = 0;
/** */
private int image = 0;
/** */
private int index = 0;
/** */
private int last = 0;
/** */
private final static String IMAGE_PATH = "images/channels/";
/** */
private final static String IMAGE_EXT = ".jpg";
/** constant for the channel header name */
public final static String BUSINESS_LABEL = "business";
/** constant for the channel header name */
public final static String COMMERCIAL_LABEL = "commercial";
/** constant for the channel header name */
public final static String MRO_LABEL = "mro";
/** constant for the channel header name */
public final static String DEFENSE_LABEL = "defense";
/**
*
*/
public enum CHANNEL_NAME {
BUSINESS (BUSINESS_LABEL, DocumentSummary.BA_ID, "bus"),
COMMERCIAL (COMMERCIAL_LABEL, DocumentSummary.CA_ID, "_com"),
MRO (MRO_LABEL, DocumentSummary.MRO_ID, "mro"),
DEFENSE (DEFENSE_LABEL, DocumentSummary.DEFENSE_ID, "mil");
/** */
public String label;
/** */
public int ID;
/** */
public String prefix;
/** */
private CHANNEL_NAME(String label, int ID, String prefix) {
this.label = label.toUpperCase();
this.ID = ID;
this.prefix = prefix;
}
};
/**
*
*/
private String nextRandomImage() {
while(index == last) {
index = Random.nextInt(channels.size()) + 1;
}
last = index;
return String.valueOf(index);
}
/**
*
*/
public static List<String> channelNames() {
ArrayList<String> channels = new ArrayList<String>(CHANNEL_NAME.values().length);
for(int i=0; i<channels.size(); i++) {
channels.add(CHANNEL_NAME.values()[i].label);
}
return channels;
}
/**
*
*/
public static int[] channelIDs() {
int[] IDs = new int[CHANNEL_NAME.values().length];
for(int i=0; i<IDs.length; i++) {
IDs[i] = CHANNEL_NAME.values()[i].ID;
}
return IDs;
}
/**
*
* #return
*/
public static int channelCount() {
return CHANNEL_NAME.values().length;
}
/**
*
*/
public static Date cutoffDate() {
Date date = new Date();
CalendarUtil.addDaysToDate(date, DEFAULT_DASHBOARD_HISTORY_IN_DAYS);
return date;
}
/**
* Constructor
*/
public DashboardChannelSummary() {
}
/**
* Constructor
*/
public DashboardChannelSummary(ArrayList<ArrayList<DocumentSummary>> channels) {
this.channels = channels;
}
/**
*
*/
public String nextImageURL() {
if(++image > channels.get(channel - 1).size()) {
image = 0;
}
return GWT.getHostPageBaseURL() +
IMAGE_PATH +
CHANNEL_NAME.values()[channel - 1].prefix +
nextRandomImage() +
IMAGE_EXT;
}
/**
*
*/
public ArrayList<DocumentSummary> nextChannel() {
return channels.get(channel++);
}
/**
*
*/
public String toString() {
return this.getClass().toString() + " current channel : " + channel;
}
}
The culprit is most likely DashboardChannelSummary. To be sure, change the return type of getChannelSummary to something "safe", like String or just Void. If the error persists, there's an issue with the service's configuration (though, I doubt it would come up during GWT's compilation phase). If this service works, then you can be pretty sure that it's because DashboardChannelSummary is not serializable.
While the class itself has a no-args constructor and implements IsSerializable, not all the fields are serializable. You should have a closer look at the Channel class (maybe DocumentSummary too, but there's no code for it provided in the question) and the Iterator fields (ArrayList returns an Itr instance, which doesn't seem to be serializable).
If the error still persists, try simplifying DashboardChannelSummary until you get a working version and then work your way "up", until you find the part that is causing the error.

Get product name from Array list object

I'm creating small javaEE Application I have problem with vendorsProdcut name dropdownbox is not showing name only array object like this see the images
Just want to ask how can I get the product name from arraylist to fix my problem?
just wondering is there are away to bring arraylist product name from
productViewModel.getAllProductForVendor
HTML
<div class="ui-block-a">
<h:selectOneMenu id="productname" value="#{productViewModel.prodname}" onchange="javascript: return this.form.submit();">
<f:selectItems value="#{productViewModel.getAllProductForVendor(vendorViewModel.vendorno)}"></f:selectItems>
</h:selectOneMenu>
</div>
Java Beans
public ArrayList<ProductEJBDTO> getAllProductForVendor(int vendorno) {
ArrayList<ProductEJBDTO> Products = new ArrayList() ;
//model.getProducts(vendorno);
try
{
Products = productFacadeBean.getAllProductsForVendor(vendorno);
}
catch(Exception e)
{
System.out.println("can't get products for vendors " + e);
}
return Products;
}
DTO
package case2dtos;
import java.io.Serializable;
import java.math.BigDecimal;
/**
*
* #author abdallaelnajjar
*/
public class ProductEJBDTO implements Serializable {
public ProductEJBDTO(){}
private int vendorno;
private String prodcd;
private String vensku;
private String prodnam;
private BigDecimal costprice;
private BigDecimal msrp;
private int rop;
private int eoq;
private int qoh;
private int qoo;
private byte[] qrcode;
/**
* #return the prodcd
*/
public String getProdcd() {
return prodcd;
}
/**
* #param prodcd the prodcd to set
*/
public void setProdcd(String prodcd) {
this.prodcd = prodcd;
}
/**
* #return the vensku
*/
public String getVensku() {
return vensku;
}
/**
* #param vensku the vensku to set
*/
public void setVensku(String vensku) {
this.vensku = vensku;
}
/**
* #return the prodnam
*/
public String getProdnam() {
return prodnam;
}
/**
* #param prodnam the prodnam to set
*/
public void setProdnam(String prodnam) {
this.prodnam = prodnam;
}
/**
* #return the costprice
*/
public BigDecimal getCostprice() {
return costprice;
}
/**
* #param costprice the costprice to set
*/
public void setCostprice(BigDecimal costprice) {
this.costprice = costprice;
}
/**
* #return the msrp
*/
public BigDecimal getMsrp() {
return msrp;
}
/**
* #param msrp the msrp to set
*/
public void setMsrp(BigDecimal msrp) {
this.msrp = msrp;
}
/**
* #return the rop
*/
public int getRop() {
return rop;
}
/**
* #param rop the rop to set
*/
public void setRop(int rop) {
this.rop = rop;
}
/**
* #return the eoq
*/
public int getEoq() {
return eoq;
}
/**
* #param eoq the eoq to set
*/
public void setEoq(int eoq) {
this.eoq = eoq;
}
/**
* #return the qoh
*/
public int getQoh() {
return qoh;
}
/**
* #param qoh the qoh to set
*/
public void setQoh(int qoh) {
this.qoh = qoh;
}
/**
* #return the qoo
*/
public int getQoo() {
return qoo;
}
/**
* #param qoo the qoo to set
*/
public void setQoo(int qoo) {
this.qoo = qoo;
}
/**
* #return the qrcode
*/
public byte[] getQrcode() {
return qrcode;
}
/**
* #param qrcode the qrcode to set
*/
public void setQrcode(byte[] qrcode) {
this.qrcode = qrcode;
}
/**
* #return the vendorno
*/
public int getVendorno() {
return vendorno;
}
/**
* #param vendorno the vendorno to set
*/
public void setVendorno(int vendorno) {
this.vendorno = vendorno;
}
}
Override the toString() method in the ProductEJBDTO to return the name.
public class ProductEJBDTO implements Serializable {
...
...
#Override
public String toString() {
return this.prodnam; // The product name you want to display.
}
}
Use the itemLabel attribute (docs):
<f:selectItems value="..." var="x" itemLabel="#{x.prodnam}"></f:selectItems>
(I assume the prodnam property is the desired display name; any EL expression will do though)

Having some trouble with the BlackJack Java card total ouptput

So I am creating this BlackJack Java game that uses many different classes to learn how to program using OO. I'm really stuck on this one particular part however, getting the code to display the correct card in the hand. It just displays a weird string such as com.game.blackjack.Hand#18e2b22, or has a different display of characters. Wondering how this can be converted into an actual card value and rank?
public class Suit {
public static final int SPADE = 0, HEART = 1, DIAMOND = 2, CLUB = 3;
/**
* Maps the names for the suits as a string.
*/
private Map<Integer, String> suitMap = new HashMap<Integer, String>();
/**
* ID for the suit
*/
private int suitId = 0;
/**
* sets the id for the suit to get.
*/
public Suit(int suitId) {
suitMap.put(SPADE, "Spades");
suitMap.put(HEART, "Hearts");
suitMap.put(DIAMOND, "Diamonds");
suitMap.put(CLUB, "Clubs");
this.suitId = suitId;
}
public String toString() {
return suitMap.get(suitId);
}
/**
* #param suitId
* #return suitMap
*/
public String getSuitNameById(int suitId) {
return suitMap.get(suitId);
}
/**
* #return id of suit
*/
public String getSuitName() {
return suitMap.get(suitId);
}
/**
* #return the suitId
*/
public int getSuitId() {
return suitId;
}
/**
* #param suitId the suitId to set
*/
public void setSuitId(int suitId) {
this.suitId = suitId;
}
/**
* #return the suitMap
*/
public Map<Integer, String> getSuitMap() {
return suitMap;
}
/**
* #param suitMap the suitMap to set
*/
public void setSuitMap(Map<Integer, String> suitMap) {
this.suitMap = suitMap;
}
}
public class Card {
private boolean stateOfCard = false;
/**
* Gives the constant values to ace jack queen and king for being special
* types of cards.
*/
public final static int ACE = 1, JACK = 11, QUEEN = 12, KING = 13;
/**
* Maps names to the ace jack queen and king cards.
*/
private Map<Integer, String> nameMap = new HashMap<Integer, String>();
/**
* Rank or type of card (2-9, J,Q,K, A)
*/
private String cardRank = null;
/**
* Card suit
*/
private Suit suit = null;
/**
* Numeric value of the card
*/
private int cardValue = 0;
/**
* Gives you the suit, cardRank, and the cardValue
*/
public Card(Suit suit, String cardRank, int cardValue) {
nameMap.put(ACE, "Ace");
nameMap.put(JACK, "Jack");
nameMap.put(QUEEN, "Queen");
nameMap.put(KING, "King");
if (cardValue >= 11 || cardValue == 1) cardRank = nameMap.get(cardValue);
this.suit = suit;
this.cardRank = cardRank;
this.cardValue = cardValue;
}
/**
* Displays to user the rank and suit of the card.
*/
public String toString() {
return cardRank + " of " + suit.getSuitName();
}
/**
* #return the cardRank
*/
public String getCardRank() {
return cardRank;
}
/**
* #param cardRank the cardRank to set
*/
public void setCardRank(String cardRank) {
this.cardRank = cardRank;
}
/**
* #return the suit
*/
public Suit getSuit() {
return suit;
}
/**
* #param suit the suit to set
*/
public void setSuit(Suit suit) {
this.suit = suit;
}
/**
* #return the cardValue
*/
public int getCardValue() {
return cardValue;
}
/**
* #param cardValue the cardValue to set
*/
public void setCardValue(int cardValue) {
this.cardValue = cardValue;
}
/**
* #return the nameMap
*/
public Map<Integer, String> getNameMap() {
return nameMap;
}
/**
* #param nameMap the nameMap to set
*/
public void setNameMap(Map<Integer, String> nameMap) {
this.nameMap = nameMap;
}
/**
* #return the stateOfCard
*/
public boolean isStateOfCard() {
return stateOfCard;
}
/**
* #param stateOfCard the stateOfCard to set
*/
public void setStateOfCard(boolean stateOfCard) {
this.stateOfCard = stateOfCard;
}
}
public class Deck {
/**
* Deck of cards created
*/
private ArrayList<Card> deck = new ArrayList<Card>();
/**
* Keeps track of the cards that are dealt and no longer available
*/
private List<Card> cardUsed = new ArrayList<Card>();
/**
* The array of cards in a set. Can be shuffled and drawn from. Deck of any #.
* #param cards
*/
public Deck(int numCards) {
this.createDeck(numCards, 4);
}
/**
* creates a deck that has cards in it with 4 suits of each 13 cards.
* #param numCards
* #param numSuits
*/
private void createDeck(int numCards, int numSuits) {
deck = new ArrayList<Card>();
cardUsed = new ArrayList<Card>();
if ((numCards % numSuits) > 0) return;
for (int i=0; i < numSuits; i++) {
for(int j=1; j <= (numCards / numSuits); j++) {
deck.add(new Card(new Suit(i), j + "", j));
}
}
}
/**
* Deals a card to the hand. Sends dealt card to the cardUsed list so that
* a used card will not be drawn again unless deck is shuffled.
* #return dealtCard
*/
public Card dealCard( ) {
Card dealtCard = null;
if (deck.size() == 0){
deck.addAll(cardUsed);
this.shuffle();
cardUsed = new ArrayList<Card>();
}
dealtCard = deck.get(0);
deck.remove(0);
cardUsed.add(dealtCard);
return dealtCard;
}
/**
* Shuffles the cards after every round.
*/
public void shuffle() {
Collections.shuffle(deck);
}
/**
* #return the deck
*/
public ArrayList<Card> getDeck() {
return deck;
}
/**
* #param deck the deck to set
*/
public void setDeck(ArrayList<Card> deck) {
this.deck = deck;
}
/**
* Returns the number of used cards
* #return
*/
public int getNumUsedCards() {
return cardUsed.size();
}
/**
* #return the cardUsed
*/
public List<Card> getCardUsed() {
return cardUsed;
}
/**
* #param cardUsed the cardUsed to set
*/
public void setCardUsed(List<Card> cardUsed) {
this.cardUsed = cardUsed;
}
}
public class Hand {
private ArrayList<Card> hand = new ArrayList<Card>();
int total = 0;
/**
* A list of cards that can be defined as hand. Player has a list of these
* cards in a hand.
*/
public Hand(){
}
public boolean isAce() {
return false;
}
public boolean discardHand(){
if (hand.isEmpty()) {
hand = new ArrayList<Card>();
}
return false;
}
/**
* Adds the card to the hand in a list of cards.
* #param c
*/
public void addCard(Card c) {
this.hand.add(c);
}
/**
* Gets the place value of the card in the hand.
* #param index
* #return index of card in hand
*/
public Card getPosition(int index){
return hand.get(index);
}
/**
* Gets how many cards are in the player's hand.
* #return hand size
*/
public int handCardCount(){
return hand.size();
}
/**
* #return the total
*/
public int getTotal() {
return total;
}
/**
* #param total the total to set
*/
public void setTotal(int total) {
this.total = total;
}
/**
* #return the hand
*/
public ArrayList<Card> getHand() {
return hand;
}
/**
* #param hand the hand to set
*/
public void setHand(ArrayList<Card> hand) {
this.hand = hand;
}
}
public class Player extends Person {
private Hand myCards = new Hand();
private int playerCashAmount = 100;
public Player() {
}
public Player(String name) {
this.name = name;
}
/**
* Gets the name of the user from the parent class
*/
public String getName() {
return super.getName();
}
/**
* #return the playerCashAmount
*/
public int getPlayerCashAmount() {
return playerCashAmount;
}
/**
* #param playerCashAmount the playerCashAmount to set
*/
public void setPlayerCashAmount(int playerCashAmount) {
this.playerCashAmount = playerCashAmount;
}
/**
* #return the myCards
*/
public Hand getMyCards() {
return myCards;
}
/**
* #param myCards the myCards to set
*/
public void setMyCards(Hand myCards) {
this.myCards = myCards;
}
}
public class Dealer extends Person {
private String dealCards = null;
private String playCards = null;
private String shuffleDeck = null;
private Hand computerCards = new Hand();
/**
*
*/
public Dealer() {
}
/**
* #return the dealCards
*/
public String getDealCards() {
return dealCards;
}
/**
* #param dealCards the dealCards to set
*/
public void setDealCards(String dealCards) {
this.dealCards = dealCards;
}
/**
* #return the playCards
*/
public String getPlayCards() {
return playCards;
}
/**
* #param playCards the playCards to set
*/
public void setPlayCards(String playCards) {
this.playCards = playCards;
}
/**
* #return the shuffleDeck
*/
public String getShuffleDeck() {
return shuffleDeck;
}
/**
* #param shuffleDeck the shuffleDeck to set
*/
public void setShuffleDeck(String shuffleDeck) {
this.shuffleDeck = shuffleDeck;
}
/**
* #return the computerCards
*/
public Hand getComputerCards() {
return computerCards;
}
/**
* #param computerCards the computerCards to set
*/
public void setComputerCards(Hand computerCards) {
this.computerCards = computerCards;
}
}
public class Person {
protected String name = null;
Hand h = new Hand();
/**
*
*/
public Person() {
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the h
*/
public Hand getH() {
return h;
}
/**
* #param h the h to set
*/
public void setH(Hand h) {
this.h = h;
}
}
public class GameEngine {
static Scanner in = new Scanner(System.in);
private Dealer dealer = null;
List<Player> players = new ArrayList<Player>();
Hand h = new Hand();
Person p = new Player();
Player pl = new Player();
int bet = 0;
Deck d = null;
int num = 0;
public GameEngine() {
}
/**
* Plays the game by creating a new instance of the gameplay class.
* #param args
*/
public static void main(String[] args) {
GameEngine ge = new GameEngine();
ge.gamePlay();
}
/**
* Game of BlackJack, runs all the methods that it will call to.
*/
public void gamePlay() {
// States the title of the game.
//this.welcomeToGame();
// Shuffles the deck and creates the number of cards for it.
this.deckStart();
// Prompts user for number of players.
//this.howManyPlayers(num);
// Displays welcome message and asks for user's name.
//this.greetUser();
// Deal initial cards
this.beginCardDeal();
// Place bet on the current round.
//this.betAmount(pl, bet);
// Evaluate, get player choice (stay or hit or bust)
//this.evaluatePlayer();
// Evaluate if bust.
//this.isBust();
// Deal more cards to each user.
//this.takeHitOrStay();
// All players bust / stay.
// Evaluate winner.
}
/**
* Initializes the deck and shuffles it.
*/
public void deckStart () {
d = new Deck(52);
d.shuffle();
}
/**
* Displays welcome message to the player.
*/
public void welcomeToGame(){
System.out.println("This is BlackJack (Double Exposure)\n\n");
}
/**
* Asks for name input and then welcomes them with name.
*/
public void greetUser() {
System.out.print("Enter your name: ");
p.setName(in.next());
System.out.println("Welcome, " + p.getName() + ".");
}
/**
* Prompts user to input how many opponents they would like to face in the game of BlackJack.
* #param num
*/
public void howManyPlayers(int num) {
players = new ArrayList<Player>();
System.out.print("How many other players would you like for this game? Enter here: ");
num = in.nextInt();
for (int i=0; i < num; i++) {
players.add(new Player("Player " + i));
System.out.println(players);
}
}
/**
* Asks the player how much money they will bet on the hand.
* #param pl
* #param bet
*/
public void betAmount(Player pl, int bet) {
while (bet == 0 || bet > pl.getPlayerCashAmount()) {
System.out.print("You have $" + pl.getPlayerCashAmount() + " as of now. Please enter a bet amount: ");
bet = in.nextInt();
System.out.println("You are going to bet $" + bet + ".");
if (bet < 0 || bet > pl.getPlayerCashAmount())
System.out.println("\nYour answer must be between $0 and $" + pl.getPlayerCashAmount());
else if (bet == pl.getPlayerCashAmount())
System.out.println("All in!");
}
}
/**
* Deals the cards to each of the players.
*/
public void beginCardDeal () {
for (int x = 0; x < 2; x++) {
System.out.print("\nDealer is dealing a card. . . \n");
d.dealCard();
System.out.println("\nYour hand: " + pl.getMyCards());
//System.out.println("New hand value test::: " + pl.getMyCards().addCard(d.dealCard()));
}
}
/**
* Checks to see if the player's hand value is over 21. If yes then player
* loses that round.
*/
public void isBust(){
if (h.getTotal() > 21) {
System.out.println("Sorry, you have gone over 21 and busted.");
int money = pl.getPlayerCashAmount() - bet;
System.out.println("You lost $"+bet+", and now you have "+money);
}
}
/**
* Counts the total value of cards each player holds in their hand.
*/
public void evaluatePlayer(){
System.out.println("Your hand value is: ");
System.out.println(pl.getMyCards().getTotal());
}
public String takeHitOrStay(){
while (pl.getMyCards().getTotal() < 21){
System.out.println("Would you like to hit[h] or stay[s]? ");
String choice = in.next();
if (choice.equalsIgnoreCase("h")){
pl.getMyCards();
//System.out.println(pl.getMyCards());
if (choice.equalsIgnoreCase("s")){
System.out.println("Null");
//finish this.
}
}
return choice;
}
return null;
}
/**
* #return the deck
*/
public Deck getDeck() {
return d;
}
/**
* #param deck the deck to set
*/
public void setDeck(Deck deck) {
this.d = deck;
}
/**
* #return the player
*/
public Player getPlayer() {
return pl;
}
/**
* #param player the player to set
*/
public void setPlayer(Player player) {
this.pl = player;
}
/**
* #return the dealer
*/
public Dealer getDealer() {
return dealer;
}
/**
* #param dealer the dealer to set
*/
public void setDealer(Dealer dealer) {
this.dealer = dealer;
}
}
The new problem I am having is that the result I am getting is now null of Spades or 0 of Spades as an output. I added a toString() function into the Hand class.
public String toString(){
return c.getCardValue() + " of " + s.getSuitName();
}
So this has been added to Hand and cleared my first problem of only getting the Hash code for each output. Any ideas on Why I am getting the null of Spades as an output?
You've overridden toString on many classes, but not (yet) on the Hand class. Override toString on Hand to provide your own custom string conversion, or else you'll get the Object implementation of toString, which is to use the class name, an # sign, and the address of the object.
To quote the Javadocs:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())

Categories

Resources