I want my program print all the entries in HashMap, and it does if I run the app in debugger. But if I run it normaly it prints only the last entry :(
Have no idea why it does,
Please help me.
MoneyCounter:
package home.lib;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import home.interfaces.GoodsOper;
import home.interfaces.WalletOper;
import home.interfaces.WastesListOper;
public class MoneyCounter implements WastesListOper, WalletOper, GoodsOper {
private ArrayList<String> wastesPrint = new ArrayList<>();
private Map<GregorianCalendar, Good> wastesMap = new HashMap<GregorianCalendar, Good>();
private Map<String, Good> goodsMap = new HashMap<String, Good>();
private Map<String, Wallet> walletsMap = new HashMap<String, Wallet>();
private Wallet currentWallet;
private Good currentGood;
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
/**
* Provides selling (returning) of specified good puts the good
* to the wastesMap by date
* #param goodName
*/
#Override
public void sell(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
putMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Provides buying specified good puts the good you've bought
* to the wastesMap by date
* #param goodName
*/
#Override
public void buy(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
takeMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Add a new Wallet to the list if there is no the same one
* #param name
* #param currency
*/
#Override
public void createWallet(String name, String currency) {
walletsMap.putIfAbsent(name, new Wallet(name, currency));
}
/**
* Adds a new Good to the list with specified price
* #param name
* #param price
*/
#Override
public void createGood(String name, int price) {
goodsMap.putIfAbsent(name, new Good(name, price));
}
/**
* Returns array of strings with goods specifications, which
* satisfies the interval [startPrice, endPrice]
* #param startPrice
* #param endPrice
* #return array of strings String[]
*/
#Override
public String[] goodsListToStringByPrice(int startPrice, int endPrice) {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
if (e.getValue().getPrice() >= startPrice && e.getValue().getPrice() <= endPrice) {
goods[i++] = e.getValue().goodToString();
}
}
return goods;
}
/**
* Returns an array of Strings with goods descriptions
* #return array of strings String[]
*/
#Override
public String[] goodsListToString() {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
goods[i++] = e.getValue().goodToString();
}
return goods;
}
/**
* Replaces old Wallet's name with new one specified if one's name is absent
* #param oldName
* #param newName
*/
public void changeWalletName(String oldName, String newName) {
walletsMap.putIfAbsent(newName, new Wallet(newName, walletsMap.get(oldName)));
walletsMap.remove(oldName);
}
/**
* Returns an array of Strings with wallet descriptions
* #return array of strings String[]
*/
public String[] walletListToString() {
String[] wallets = new String[walletsMap.size()];
int i = 0;
for (Map.Entry<String, Wallet> e : walletsMap.entrySet()) {
wallets[i++] = e.getValue().walletToString();
}
return wallets;
}
/**
* Returns the wallet's money balance by name
* #param walletName
* #return String
*/
public String checkWallet(String walletName) {
return walletsMap.get(walletName).walletToString();
}
/**
* Deletes the wallet, specified by name from wallet list
* #param walletName
*/
#Override
public void delWallet(String walletName) {
walletsMap.remove(walletName);
}
/**
* Deletes the good, specified by name from good list
* #param goodName
*/
#Override
public void delGood(String goodName) {
goodsMap.remove(goodName);
}
/**
* Use this method to put more money to the wallet
* got payment for example
* #param count
*/
#Override
public void putMoney(int count) {
currentWallet.addMoney(count);
}
/**
* Use this method if you need money but not for buying a good
* #param count
*/
#Override
public void takeMoney(int count) {
currentWallet.getMoney(count);
}
/**
* Returns list of all wallets
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToString() {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
array.add(entry.getValue().walletToString());
}
return array;
}
/**
* Returns list of wallets specified by currency
* #param currency
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToStringByCurrency(String currency) {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
if (entry.getValue().getCurrency().equals(currency)) {
array.add(entry.getValue().walletToString());
}
}
return array;
}
/**
* Chooses wallet to operate with when you bus, sell, etc.
* #param walletName
*/
#Override
public void chooseTheWallet(String walletName) {
if (walletsMap.containsKey(walletName)) {
this.currentWallet = walletsMap.get(walletName);
}
}
/**
* Returns list of strings of all money wastes you've ever done
* #return ArrayList wastesPrint
*/
#Override
public void wastesListFillUp() {
for(Map.Entry<GregorianCalendar, Good> entry:wastesMap.entrySet()){
this.wastesPrint.add(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Is used for tests
* #throws IOException
*/
public void printAllList() throws IOException {
for (Map.Entry<GregorianCalendar, Good> entry : wastesMap.entrySet()) {
System.out.println(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Changes the specified good's price
* #param price
*/
#Override
public void changePrice(int price) {
currentGood.changePrice(price);
}
/**
* Chooses the good for operations
* #param goodName
*/
#Override
public void chooseTheGood(String goodName) {
if (goodsMap.containsKey(goodName)) {
this.currentGood = goodsMap.get(goodName);
}
}
}
Main:
package home.main;
import java.io.IOException;
import home.lib.MoneyCounter;
public class Main {
public static void main(String[] args) throws IOException {
MoneyCounter application = new MoneyCounter();
application.createGood("Snikers", 850);
application.createGood("Хрень какая-то", 1000);
application.createWallet("Основоной счет", "UAH");
application.chooseTheWallet("Основоной счет");
application.buy("Snikers");
application.buy("Хрень какая-то");
application.printAllList();
}
}
Wallet:
package home.lib;
public class Wallet {
// all money is kept
private int moneyCount;
private int debt;
private String currency;
private String name;
// constructor for new Wallet
public Wallet(String walletName, String currencyName) {
this.currency = currencyName;
this.moneyCount = 0;
this.debt = 0;
this.name = walletName;
}
// for renaming Wallet in WalletList
public Wallet(String walletName, Wallet oldWallet) {
this.name = walletName;
this.moneyCount = oldWallet.getMoneyCount();
this.debt = oldWallet.getDebt();
this.currency = oldWallet.getCurrency();
}
// actions with money
public void addMoney(int moneyCount) {
if (this.moneyCount >= 0 && this.debt == 0) {
this.moneyCount += moneyCount;
} else {
moneyCount -= this.debt;
this.debt = 0;
this.moneyCount = moneyCount;
}
}
public void getMoney(int moneyCount) {
if (this.debt == 0 && this.moneyCount > 0 && this.moneyCount >= moneyCount) {
this.moneyCount -= moneyCount;
} else {
moneyCount -= this.moneyCount;
this.moneyCount = 0;
this.debt += moneyCount;
}
}
// getters/setters block
public int getMoneyCount() {
return this.moneyCount;
}
public int getDebt() {
return this.debt;
}
public String getName() {
return this.name;
}
public String getCurrency() {
return this.currency;
}
public String walletToString() {
return this.debt <= 0 ? "("+this.name + " Остаток: " + (double)this.moneyCount/100 + " " + this.currency+")"
: "("+this.name + " Долг: -" + (double)this.debt/100 + " " + this.currency+")";
}
}
Good:
package home.lib;
public class Good {
private int price;
private String name;
public Good(String goodName, int goodPrice) {
this.name = goodName;
this.price = goodPrice;
}
public int getPrice() {
return this.price;
}
public double getPriceInDouble() {
return (double)this.price / 100;
}
public void changePrice(int price) {
this.price = price;
}
public String getName() {
return this.name;
}
public String goodToString() {
return "Товар: " + this.name + " | Цена: " + (double) this.price / 100;
}
}
I've got an answer. I used GregorainCalendar as a HashMap key. So, when I was starting program normaly, it was done in no time. So it was adding different values for ONE key. When you run the program in debugger you can't press next step 10 times in one moment so the time is different, so the keys are different too, so it returns all entries.
Be attentive when use time and all will be Ok :)
Related
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.
I have a static ArrayList (masterLog) that is in my main driver class. The ArrayList contains Event objects, the Event object has an ArrayList (heats) as a global variable. the heat object as an ArrayList (racers) as a global variable. Now when I have the following line of code:
System.out.println(ChronoTimer1009System.getMasterLog().get(0).getHeats().get(getCurHeat()).getRacers().toString());
this returns [] even though the getRacers() IS NOT empty!
When I call this:
System.out.println(getHeats().get(getCurHeat()).getRacers());
this returns the proper filled array.
I think I need to sync the masterLog ArrayList but I am unsure how. I have tried syncing it the way other threads on Stack Exchange have recommended but no luck.
it seems like the static ArrayList masterLog is updated two levels deep but not three levels deep if that makes sense.
What am I doing wrong?
UPDATE:
Maybe this will help explain:
In my main (driver) class, I have a static ArrayList called masterLog. The purpose of this ArrayLIst is to store instances of Event objects for later data retrieval. Now, without making it too complicated, the Event class contains an ArrayList called heats, and the Heat class contains an ArrayList called racers. When I access the masterLog ArrayList at some point in the program (when the other ArrayLists are populated with data), say for example by the call "masterLog.getHeats().get(0).getRacers()", the masterLog does not find any data in the racers ArrayList. It does, however, find data in the heats ArrayList. In other words, the object instance that is stored in the masterLog only updates information to a depth of 2 (not 3 if that makes sense).
UPDATE:
Here is some code:
ChronoTimer1009System class (driver)
package main;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
public class ChronoTimer1009System {
private Event curEvent;
private static Channel[] channels = new Channel[8];
private boolean state;
private static Stack<Log> log;
private static ArrayList<Event> masterLog;
private static Printer p;
public static Time globalTime;
private int oldLogSize; //used only in this.export()
public ChronoTimer1009System() throws UserErrorException{
for(int i=0; i<channels.length; ++i){channels[i] = new Channel(SensorType.NONE);} // initialize channels
masterLog = new ArrayList<Event>(); //this holds references to each event
this.newEvent(EventType.IND);
this.state = false; //system is initally off
log = new Stack<Log>();
p = new Printer();
globalTime = null;
oldLogSize = 0;
}
public void newEvent(EventType e) throws UserErrorException {
switch(e){
case IND: this.curEvent = new IND();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case PARIND: this.curEvent = new PARIND();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case GRP: this.curEvent = new GRP();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case PARGRP: this.curEvent = new PARGRP();ChronoTimer1009System.masterLog.add(this.curEvent);break;
}
for(Channel x : channels){if(x.getState()) x.toggleState();}
}
public void on() throws UserErrorException{
if(state) throw new IllegalStateException();
this.curEvent = new IND();
ChronoTimer1009System.globalTime = new Time(0);
state = true;
}
public void reset() throws UserErrorException{
if(state) state = false;
on();
}
public void exit(){
this.curEvent = null;
ChronoTimer1009System.globalTime = null;
if(!state) throw new IllegalStateException();
state = false;
}
public static Time searchElapsedByID(int idNum){
Time toReturn = null;
for(Log item : log){
if(item.getCompetitorNumber() == idNum){
toReturn = item.getElapsedTime(); break;
}
}
return toReturn;
}
/**
* #return the curEvent
*/
public Event getCurEvent() {
return curEvent;
}
/**
* #return the state
*/
public boolean isState() {
return state;
}
public static Channel getChan(int chan){
if(chan < 1 || chan > 8) throw new IllegalArgumentException("Argument is not in range");
return channels[chan-1];
}
public static void export(){
//*****FORMAT JSON*****
//before formating, a sort of the runners within each heat is needed to determine place.
String toJson = "{\"events\":[";
System.out.println(ChronoTimer1009System.getMasterLog().get(0).getHeats().get(0).getRacers().size());
//iterate through each event
for(int i = 0; i < ChronoTimer1009System.getMasterLog().size(); ++i){
//iterate through each heat of each event
toJson += "{\"name\":\"" + ChronoTimer1009System.getMasterLog().get(i).getType().toString() + "\",\"heats\":[";
for(int j = 0; j < ChronoTimer1009System.getMasterLog().get(i).getHeats().size(); ++j){
//iterate through each competitor in each heat
toJson += "{\"runners\":[";
System.out.println(ChronoTimer1009System.getMasterLog().get(i).getHeats().size());
ArrayList<Competitor> x = sortByPlace(ChronoTimer1009System.getMasterLog().get(i).getHeats().get(j).getRacers()); <----- on this line, the getRacers() part has a size of zero when it isn't empty.
for(int k = 0; k < x.size(); ++k){
//notice we are working with a sorted copy
//TODO make Competitor endTime the elapsed time
toJson += "{\"place\":\"" + String.valueOf(k+1) + "\",\"compNum\":\"" + x.get(k).getIdNum() + "\", \"elapsed\":\"" + x.get(k).getEndTime().toString() + "\"},";
}
toJson += "]},";
}
toJson += "]},";
}
toJson += "}";
System.out.println(toJson);
/*try{
URL site = new URL("http://7-dot-eastern-cosmos-92417.appspot.com/chronoserver");
HttpURLConnection conn = (HttpURLConnection) site.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String data = "data=" + toJson;
out.writeBytes(data);
out.flush();
out.close();
System.out.println("Done sent to server");
new InputStreamReader(conn.getInputStream());
}
catch (Exception e)
{
e.printStackTrace();
}*/
}
private static ArrayList<Competitor> sortByPlace(ArrayList<Competitor> unsorted)
{
ArrayList<Competitor> whole = (ArrayList<Competitor>) unsorted.clone();
ArrayList<Competitor> left = new ArrayList<Competitor>();
ArrayList<Competitor> right = new ArrayList<Competitor>();
int center;
if(whole.size()==1)
return whole;
else
{
center = whole.size()/2;
// copy the left half of whole into the left.
for(int i=0; i<center; i++)
{
left.add(whole.get(i));
}
//copy the right half of whole into the new arraylist.
for(int i=center; i<whole.size(); i++)
{
right.add(whole.get(i));
}
// Sort the left and right halves of the arraylist.
left = sortByPlace(left);
right = sortByPlace(right);
// Merge the results back together.
merge(left,right,whole);
}
return whole;
}
private static void merge(ArrayList<Competitor> left, ArrayList<Competitor> right, ArrayList<Competitor> whole) {
int leftIndex = 0;
int rightIndex = 0;
int wholeIndex = 0;
// As long as neither the left nor the right arraylist has
// been used up, keep taking the smaller of left.get(leftIndex)
// or right.get(rightIndex) and adding it at both.get(bothIndex).
while (leftIndex < left.size() && rightIndex < right.size())
{
if ((left.get(leftIndex).getEndTime().compareTo(right.get(rightIndex)))<0)
{
whole.set(wholeIndex,left.get(leftIndex));
leftIndex++;
}
else
{
whole.set(wholeIndex, right.get(rightIndex));
rightIndex++;
}
wholeIndex++;
}
ArrayList<Competitor>rest;
int restIndex;
if (leftIndex >= left.size()) {
// The left arraylist has been use up...
rest = right;
restIndex = rightIndex;
}
else {
// The right arraylist has been used up...
rest = left;
restIndex = leftIndex;
}
// Copy the rest of whichever arraylist (left or right) was
// not used up.
for (int i=restIndex; i<rest.size(); i++) {
whole.set(wholeIndex, rest.get(i));
wholeIndex++;
}
}
/**
* #return the log
*/
public static Stack<Log> getLog() {
return log;
}
/**
* #return the masterLog
*/
public static ArrayList<Event> getMasterLog() {
return masterLog;
}
/**
* #return the p
*/
public static Printer getPrinter() {
return p;
}
}
Event Class:
package main;
import java.util.ArrayList;
public abstract class Event extends Display{
private ArrayList<Heat> heats;
private int curHeat; //private means only this class can modify, not the subclasses
private Competitor curComp;
private String name;
public Event(String name) throws UserErrorException{
this.name = name;
heats = new ArrayList<Heat>();
curHeat = -1;
curComp = null;
createRun();
}
/**
* This method will be used by all EventTypes and will not change
* regardless of the EventType.
* #throws UserErrorException
*/
public void createRun() throws UserErrorException{
heats.add(new Heat()); ++curHeat;
}
/**
* #return the heats
*/
public ArrayList<Heat> getHeats() {
return heats;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #return the currentHeat
*/
public int getCurHeat() {
return curHeat;
}
/**
* #return the curComp
*/
public Competitor getCurComp() {
return curComp;
}
/**
* #param curComp the curComp to set
*/
public void setCurComp(Competitor curComp) {
this.curComp = curComp;
}
/* (non-Javadoc)
* #see Display#displayHeatNumber()
*/
#Override
public String displayHeatNumber() {
// TODO Auto-generated method stub
return "Heat: " + (curHeat+1);
}
/* (non-Javadoc)
* #see Display#displayFinished()
*/
#Override
public String displayFinished() {
String toReturn = "";
boolean noRunners = true;
for(Competitor x : getHeats().get(getCurHeat()).getRacers()){
if(x.getEndTime() != null){
toReturn += "\n" + x.getIdNum() + " " + (ChronoTimer1009System.searchElapsedByID(x.getIdNum()).equals(new Time(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)) ? "DNF" : ChronoTimer1009System.searchElapsedByID(x.getIdNum()).toString() + " F");
noRunners = false;
}
}
if(noRunners){toReturn = "no runners have finished";}
return toReturn;
}
public abstract void endRun() throws UserErrorException;
public abstract void trigChan(int chan, boolean dnf) throws UserErrorException;
public abstract void cancel(int ln) throws UserErrorException;
public abstract EventType getType();
}
Heat class:
package main;
import java.util.ArrayList;
public class Heat {
private ArrayList<Competitor> racers;
//private ArrayList<Competitor> racers;
private int currentCompetitor;
/**
* Constructor
*/
public Heat(){
racers = new ArrayList<Competitor>();
//racers = new ArrayList<Competitor>();
currentCompetitor = 0;
}
/**
* Set selected racer as next on to start
* #param racer the racer to start next
*/
public void setNextCompetitor(Competitor x){
int pos = racers.indexOf(x);
if(pos == -1 || pos<currentCompetitor) throw new IllegalArgumentException("Competitor not in the race! Please add first");
for(int i = pos; i>currentCompetitor; --i){
racers.set(i, racers.get(i-1));
}
racers.set(currentCompetitor, x);
}
/**
* Take the selected runner (the next runner) out from the race
* #param racer the runner to be cleared
*/
public void clearNextCompetitor() throws UserErrorException {
if(racers.size()-(currentCompetitor)<1) throw new UserErrorException("No runners to clear!");
for(int i = currentCompetitor+1; i<racers.size(); ++i){
racers.set(i-1, racers.get(i));
}
racers.remove(racers.size()-1);
}
/**
* basically a remove method
* #param x
*/
public void remove(Competitor x){
int pos = racers.indexOf(x);
if(pos < 0) throw new IllegalArgumentException("runner does not exists");
racers.remove(pos);
}
/**
* Swaps two runners positions in line
*/
public void swap() throws UserErrorException{
int count = 0;
for(Competitor x : racers){
if(x.getStartTime() == null) ++count;
}
if(count > 1 && currentCompetitor + 1 <= racers.size()){
Competitor first = racers.get(currentCompetitor);
Competitor second = racers.get(currentCompetitor+1);
racers.set(currentCompetitor, second);
racers.set(currentCompetitor+1, first);
}
else{
throw new UserErrorException("Not enough competitors to swap");
}
}
/**
* Add a competitor to the end of the current line of competitors if any
* #param x the competitor to add
*/
public boolean addCompetitor(Competitor x) throws UserErrorException{
if(x.getIdNum() < 0 || x.getIdNum() > 99999) throw new UserErrorException("ID number out of range");
if(x.getRunNum() < 0) throw new IllegalArgumentException("Run Num Out of range");
boolean add = true;
for(Competitor i : racers){
if(i.getIdNum() == x.getIdNum()){
add = false;
break;
}
}
if(add){
racers.add(x);
}
return add;
}
/**
* Retrieve the next competitor if there is one
* #return the next competitor
*/
public Competitor getNextCompetitor() throws UserErrorException{
if(!hasNextCompetitor()) throw new UserErrorException("There are no more competitors!");
while(racers.get(currentCompetitor).isCompeting()){++currentCompetitor;}
return racers.get(currentCompetitor++);
}
/**
* used to fix the order of the queue after cancel is called
*/
public void fix(EventType x){
switch(x){
case IND:
--currentCompetitor;
break;
case GRP: case PARGRP: case PARIND:
for(int i = 0; i<racers.size(); ++i){
if(racers.get(i).getStartTime() == null){
currentCompetitor = i;
break;
}
}
break;
}
}
/**
* Is there another competitor to go?
* #return whether or not there is another competitor to go.
*/
public boolean hasNextCompetitor(){
return currentCompetitor < racers.size();
}
/**
* Return a 1D array view of the competitors
* #return
*/
public ArrayList<Competitor> getRacers(){
return racers;
}
}
in the export method of the ChronoTimer1009System class, I point out where the error is and what is happening
This table is produced by my code below. (The table's data is rubbish)
Question:
How can I get a list of the items under a certain column in the order they appear?
I want to do something like table.GetListFromColumn("carmake") so I would have ["Aston Martin" , "Porche 911", "ferrari"].
Or beanItemContainer.GetListFromColumn("carmake")?
#Override
public void init(VaadinRequest request) {
BrakeResponseTime time1 = new BrakeResponseTime(0.2f);
BrakeResponseTime time2 = new BrakeResponseTime(0.8f);
BrakeResponseTime time3 = new BrakeResponseTime(0.5f);
Collection<SportsCar>c = new ArrayList<SportsCar>();
c.add(new SportsCar("ferrari", 180.0, "Tom", time1));
c.add(new SportsCar("Aston Martin", 165.0, "Harry", time2));
c.add(new SportsCar("Porche 911", 145.0, "Dick", time3));
MyBeanItemContainer container = new MyBeanItemContainer(SportsCar.class,c);
Table table = new Table();
t.setContainerDataSource(container);
this.setContent(table);
}
.
public class BrakeResponseTime implements Comparable<BrakeResponseTime> {
float time;
/**
* Create a Demo.BrakeResponseTime.
*/
public BrakeResponseTime(float time) {
this.time = time;
}
/**
* Get the time.
*
* #return the time.
*/
public float getTime() {
return time;
}
/**
* Set the time.
*
* #param time
* the time.
*/
public void setTime(float time) {
this.time = time;
}
#Override
public String toString() {
return time +"/%";
}
/*
* (non-Javadoc)
*
* #see java.lang.Comparable#compareTo(java.lang.Object)
*/
#Override
public int compareTo(BrakeResponseTime o) {
if (null == o) {
return 1;
}
if(time==o.getTime()){
return 0;
}
return (time < o.getTime() ? -1 : 1);
}
}
.
public class MyBeanItemContainer extends BeanItemContainer<SportsCar> {
/**
* Create a Demo.MyBeanItemContainer.
*/
public MyBeanItemContainer(Class<SportsCar> type, Collection<SportsCar> collection) {
super(type, collection);
}
private int compareBrakeResponseTimeWithNullCheck(BrakeResponseTime o1, BrakeResponseTime o2) {
if (null == o1 && (null == o2)) {
return 0;
} else if (null == o1 && (null != o2)) {
return -1;
}else if(null != o1 && (null == o2)){
return 1;
} else {
return o1.compareTo(o2);
}
}
#Override
public void sort(final Object[] propertyId, final boolean[] ascending) {
super.sort(propertyId, ascending);
System.out.println(Arrays.toString(propertyId));
final boolean sortAscending = ascending[0];
final Object sortContainerPropertyId = propertyId[0];
List<SportsCar> list = super.getAllItemIds();
Collections.sort(list, new Comparator<SportsCar>() {
#Override
public int compare(final SportsCar o1, final SportsCar o2) {
int result = 0;
if ("responseTime".equals(sortContainerPropertyId)) {
result = compareBrakeResponseTimeWithNullCheck(o1.getResponseTime(), o2.getResponseTime());
}
if (!sortAscending) {
result *= -1;
}
return result;
}
});
}
}
public class SportsCar {
String carMake;
double topspeed;
String driver;
BrakeResponseTime responseTime;
public SportsCar(String carMake, double topspeed, String driver, BrakeResponseTime responseTime) {
this.carMake = carMake;
this.topspeed = topspeed;
this.driver = driver;
this.responseTime = responseTime;
}
/**
* 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 String getDriver() {
return driver;
}
/**
* Set the driver.
*
* #param driver
* the driver.
*/
public void setDriver(String driver) {
this.driver = driver;
}
/**
* Get the responseTime.
* #return the responseTime.
*/
public BrakeResponseTime getResponseTime() {
return responseTime;
}
/**
* Set the responseTime.
* #param responseTime the responseTime.
*/
public void setResponseTime(BrakeResponseTime responseTime) {
this.responseTime = responseTime;
}
}
I hadn't realised I could access the bean container's properties in this way.
container.getIdByIndex(0).getCarMake()
This is what I was looking for!
I am having some difficult on a jtable bound on a observablelist of objects called EntradaMercadoriaList. After adding all objects in this list, jtable shows only empty rows equivalent of the list size
here is my code:
List <EntradaMercadoria> merc = new ArrayList<EntradaMercadoria>();
for (int i = 0; i < entradasList.size(); i++) {
int nf = entradasList.get(i).getDocOrigem();
int tipo = entradasList.get(i).getTipoDocOrigem().getIdesPecasTipoOrigem();
String fornecedor = "não-aplicado";
if (tipo == 2) {
NfTerc nfTerc;
nfTerc = entityManager.find(NfTerc.class, entradasList.get(i).getDocOrigem());
fornecedor = nfTerc.getFornecedoresNumForn().getNumForn() + " - " + nfTerc.getFornecedoresNumForn().getCodPessoa().getNomePessoa();
}
boolean novo = true;
for (int j = 0; j < merc.size(); j++) {
if (nf == merc.get(j).getnDoc() && fornecedor.equals(merc.get(j).getFornecedor())) {
merc.get(j).setQuantidade(merc.get(j).getQuantidade() + 1.00);
novo = false;
}
}
if (novo) {
EntradaMercadoria em = new EntradaMercadoria();
em.setDataEmissao(entradasList.get(i).getDataOrigem());
em.setFornecedor(fornecedor);
em.setQuantidade(1.00);
em.setTipoDoc(tipo);
em.setnDoc(nf);
merc.add(em);
}
}
entradaMercadoriaList.clear();
entradaMercadoriaList.addAll(merc);
Here is my EntadaMercadoria object:
import java.util.Date;
/**
*
* #author Bernardo
*/
class EntradaMercadoria {
private int nDoc;
private int tipoDoc;
private String fornecedor;
private double quantidade;
private Date dataEmissao;
public EntradaMercadoria() {
}
/**
* #return the nDoc
*/
public int getnDoc() {
return nDoc;
}
/**
* #param nDoc the nDoc to set
*/
public void setnDoc(int nDoc) {
this.nDoc = nDoc;
}
/**
* #return the tipoDoc
*/
public int getTipoDoc() {
return tipoDoc;
}
/**
* #param tipoDoc the tipoDoc to set
*/
public void setTipoDoc(int tipoDoc) {
this.tipoDoc = tipoDoc;
}
/**
* #return the fornecedor
*/
public String getFornecedor() {
return fornecedor;
}
/**
* #param fornecedor the fornecedor to set
*/
public void setFornecedor(String fornecedor) {
this.fornecedor = fornecedor;
}
/**
* #return the quantidade
*/
public double getQuantidade() {
return quantidade;
}
/**
* #param quantidade the quantidade to set
*/
public void setQuantidade(double quantidade) {
this.quantidade = quantidade;
}
/**
* #return the dataEmissao
*/
public Date getDataEmissao() {
return dataEmissao;
}
/**
* #param dataEmissao the dataEmissao to set
*/
public void setDataEmissao(Date dataEmissao) {
this.dataEmissao = dataEmissao;
}
}
What is wrong? is There a way to refresh table to show data in lines?
Thanks.
I'm trying to get the values out of this JSON string but I'm having a hard time achieving this.
{"DebugLogId":"1750550","RequestId":"17505503","Result":
{"Code":"","DebugLogId":"1750550","Message":""},
"Suggestions":[
{"Ranking":"1","Score":"60","Title":"This is a test message 1"},
{"Ranking":"2","Score":"60","Title":"This is a test message 2"}
]}
What way would be easiest to access the data in 'Suggestions'? I'm using the GSON module. Ideally I would like to put it all in a HashMap.
Thanks for any help and/or suggestions!
Thanks for any help!
Hope this helps:
App.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.Gson;
public class App {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = "{\"DebugLogId\":\"1750550\",\"RequestId\":\"17505503\",\"Result\":{\"Code\":\"\",\"DebugLogId\":\"1750550\",\"Message\":\"\"},\"Suggestions\":[{\"Ranking\":\"1\",\"Score\":\"60\",\"Title\":\"This is a test message 1\"},{\"Ranking\":\"2\",\"Score\":\"60\",\"Title\":\"This is a test message 2\"}]}";
Debug obj = (Debug) gson.fromJson(jsonString, Debug.class);
System.out.println(obj.getSuggestionList().get(1).getTitle());
}
}
Debug.java:
package sg.java.play_sof_json_6596072;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class Debug {
#SerializedName("DebugLogId")
private String debugLogId;
#SerializedName("RequestId")
private String requestId;
#SerializedName("Result")
private Result result;
#SerializedName("Suggestions")
private List<Suggestion> suggestionList;
/**
* #return the debugLogId
*/
public final String getDebugLogId() {
return this.debugLogId;
}
/**
* #param debugLogId the debugLogId to set
*/
public final void setDebugLogId(String debugLogId) {
this.debugLogId = debugLogId;
}
/**
* #return the requestId
*/
public final String getRequestId() {
return this.requestId;
}
/**
* #param requestId the requestId to set
*/
public final void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* #return the result
*/
public final Result getResult() {
return this.result;
}
/**
* #param result the result to set
*/
public final void setResult(Result result) {
this.result = result;
}
/**
* #return the suggestionList
*/
public final List<Suggestion> getSuggestionList() {
return this.suggestionList;
}
/**
* #param suggestionList the suggestionList to set
*/
public final void setSuggestionList(List<Suggestion> suggestionList) {
this.suggestionList = suggestionList;
}
}
Result.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("Code")
private String code;
#SerializedName("DebugLogId")
private String debugLogId;
#SerializedName("Message")
private String messahe;
/**
* #return the code
*/
public final String getCode() {
return this.code;
}
/**
* #param code the code to set
*/
public final void setCode(String code) {
this.code = code;
}
/**
* #return the debugLogId
*/
public final String getDebugLogId() {
return this.debugLogId;
}
/**
* #param debugLogId the debugLogId to set
*/
public final void setDebugLogId(String debugLogId) {
this.debugLogId = debugLogId;
}
/**
* #return the messahe
*/
public final String getMessahe() {
return this.messahe;
}
/**
* #param messahe the messahe to set
*/
public final void setMessahe(String messahe) {
this.messahe = messahe;
}
}
Suggestion.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.annotations.SerializedName;
public class Suggestion {
#SerializedName("Ranking")
private String ranking;
#SerializedName("Score")
private String score;
#SerializedName("Title")
private String title;
/**
* #return the ranking
*/
public final String getRanking() {
return this.ranking;
}
/**
* #param ranking the ranking to set
*/
public final void setRanking(String ranking) {
this.ranking = ranking;
}
/**
* #return the score
*/
public final String getScore() {
return this.score;
}
/**
* #param score the score to set
*/
public final void setScore(String score) {
this.score = score;
}
/**
* #return the title
*/
public final String getTitle() {
return this.title;
}
/**
* #param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
}
I'm recommend you to use flexjson library http://flexjson.sourceforge.net/
IMHO, it more simple and usable library. I has used GSON first time, but then switched all my projects to flexjson instead of GSON.
Using the standard json classes in android:
JSONObject o = new JSONObject("your string");
JSONArray a = o.getJSONArray("Suggestions");
int i = 0;
while ( i < a.length())
{
o = a.getJSONObject(i);
//do something with o, like o.getString("Title") ...
++i;
}
Ideally I would like to put it all in a HashMap.
If you can switch libraries, Jackson can achieve that with just one line of code.
Map map = new ObjectMapper().readValue(json, Map.class);
This would deserialize any JSON object into a HashMap, composed of just Java SE components. I haven't yet seen another Java-to/from-JSON library that can do that.
The same can be accomplished with Gson, but it requires a few more lines of code. Here's one such solution.
JsonElement je = new JsonParser().parse(json);
JsonObject jo = je.getAsJsonObject();
Map<String, Object> map = createMapFromJsonObject(jo);
// ...
static Map<String, Object> createMapFromJsonObject(
JsonObject jo)
{
Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, JsonElement> entry : jo.entrySet())
{
String key = entry.getKey();
JsonElement value = entry.getValue();
map.put(key, getValueFromJsonElement(value));
}
return map;
}
static Object getValueFromJsonElement(JsonElement je)
{
if (je.isJsonObject())
{
return createMapFromJsonObject(je.getAsJsonObject());
}
else if (je.isJsonArray())
{
JsonArray array = je.getAsJsonArray();
List<Object> list = new ArrayList<Object>(array.size());
for (JsonElement element : array)
{
list.add(getValueFromJsonElement(element));
}
return list;
}
else if (je.isJsonNull())
{
return null;
}
else // must be primitive
{
JsonPrimitive p = je.getAsJsonPrimitive();
if (p.isBoolean()) return p.getAsBoolean();
if (p.isString()) return p.getAsString();
// else p is number, but don't know what kind
String s = p.getAsString();
try
{
return new BigInteger(s);
}
catch (NumberFormatException e)
{
// must be a decimal
return new BigDecimal(s);
}
}
}
(I copied this code from my blog post at http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html.)