calculating with java with two file program - java

I have a question on how to calculate with java. In my case, I think I am doing the calculations right, but when I run it, I get a few 0s and some absurd number. How can I fix this? Any help will be greatly appreciated. Below is my code:
public class CO2Footprint {
private int NumberOfPeople, CO2PerPerson, lightBulbs, months;
private double TotalEmission, ReductionPerPaper, ReductionPerPlastic,
ReductionPerGlass, ReductionPerCan, TotalReduction,
FamilyNetEmission, annualGasoline, electricityBill
, lightBulbsRecycled, annualFuelUse, averageMonthlyCostElec,
emissionFactor, monthlyCostSeptElec, monthlyCostOct, monthlyCostNov,
averagePricePerKilowatt, totalWaste, elecPrice, NetEmission;
private boolean paper, plastic, glass, can;
CO2Footprint(int numPeople, boolean bpaper, boolean bplastic, boolean
bglass, boolean bcans, double annuallGasoline
, double electricityyPrice, int lighttBulbs){
NumberOfPeople = 0;
paper = bpaper;
plastic = bplastic;
glass = bglass;
can = bcans;
ReductionPerPaper = 184;
CO2PerPerson = 1018;
ReductionPerPlastic = 25.6;
ReductionPerGlass = 46.6;
ReductionPerCan = 165.8;
TotalEmission = 0;
annualGasoline = 16.5;
electricityBill = 0;
lightBulbs = 10;
lightBulbsRecycled = 0;
annualFuelUse = 0;
averageMonthlyCostElec = 0;
emissionFactor = 1.37;
monthlyCostSeptElec = 551.51;
monthlyCostOct = 392.84;
monthlyCostNov = 445.42;
months = 12;
averagePricePerKilowatt = 4.83;
totalWaste = 0;
NetEmission = 0.0;
}
// method for calculating total emission
public double totalEmission(){
TotalEmission = NumberOfPeople * CO2PerPerson;
return TotalEmission;
}
// method for calculating CO2 reduction
public double reduction(){
TotalReduction = 0;
ReductionPerPaper = 0;
ReductionPerPlastic = 0;
ReductionPerGlass = 0;
ReductionPerCan = 0;
if(paper = true){
ReductionPerPaper = 184;
}else{
ReductionPerPaper = 0;
}
if(plastic = true){
ReductionPerPlastic = 25.6;
}else{
ReductionPerPlastic = 0;
}
if(glass = true){
ReductionPerGlass = 46.6;
}else{
ReductionPerGlass = 0;
}
if(can = true){
ReductionPerCan = 165.8;
}else{
ReductionPerCan = 0;
}
TotalReduction = ReductionPerPaper + ReductionPerPlastic +
ReductionPerGlass + ReductionPerCan + (lightBulbs * 1.37 * 73);
return TotalReduction;
}
public double calcAnnualFuelUseGallonCO2(){
annualFuelUse = annualGasoline * 12 * 12;
return annualFuelUse;
}
public double calcElectricityBill(){
return (averageMonthlyCostElec / averagePricePerKilowatt) * emissionFactor * months;
}
public double electrictyPrice(){
return averagePricePerKilowatt;
}
public double calcWaste(){
TotalReduction = 0;
ReductionPerPaper = 0;
ReductionPerPlastic = 0;
ReductionPerGlass = 0;
ReductionPerCan = 0;
if(paper = true){
ReductionPerPaper = 184;
}else{
ReductionPerPaper = 0;
}
if(plastic = true){
ReductionPerPlastic = 25.6;
}else{
ReductionPerPlastic = 0;
}
if(glass = true){
ReductionPerGlass = 46.6;
}else{
ReductionPerGlass = 0;
}
if(can = true){
ReductionPerCan = 165.8;
}else{
ReductionPerCan = 0;
}
totalWaste = ReductionPerPaper + ReductionPerPlastic +
ReductionPerGlass + ReductionPerCan;
return totalWaste;
}
public double calcBulbsEmissionReduction(){
return lightBulbs * 1.37 * 73;
}
public double calcNetEmission(){
NetEmission = TotalEmission - CO2PerPerson;
return NetEmission;
}
}
If it helps, below is the code for how I called the methods:
import java.util.ArrayList;
public class CO2FootprintTester {
public static void main(String args[]){
ArrayList<CO2Footprint> CO2 = new ArrayList<CO2Footprint>();
CO2.add(new CO2Footprint(1, true, true, true, true, 16.5, 4.83, 10));
CO2Footprint data;
for(int i = 0; i < CO2.size(); i++){
data = CO2.get(i);
data.calcAnnualFuelUseGallonCO2();
data.calcBulbsEmissionReduction();
data.calcElectricityBill();
data.calcWaste();
data.electrictyPrice();
data.reduction();
data.totalEmission();
}
// create table
System.out.println("___________________________________________________"
+ "_____________________________________________________________________________");
System.out.printf("%65s%44s%n", " Pounds of CO2 Emitted From: |",
" Pounds of CO2 Reduced From: ");
System.out.println("___________________________________________________"
+ "_____________________________________________________________________________");
System.out.printf("%1s%25s%25s%25s%25s%n%n", "Gas", "Electricity",
"Waste", "Recycling", "New Bulbs");
// call methods
for(int i = 0; i < CO2.size(); i++){
data = CO2.get(i);
System.out.printf("%5.5f%15.5f%15.5f%15.5f%15.5f", data.calcAnnualFuelUseGallonCO2(), data.calcElectricityBill(),
data.totalEmission(), data.calcNetEmission(), data.calcBulbsEmissionReduction());//,
//data.calcElectricityBill(), data.totalEmission(), data.calcNetEmission(),
//data.calcBulbsEmissionReduction());
}
}
}

Seems like you are facing the problem of using double data type precision. double data type is sometimes troublesome in precision calculations like monetary values etc.
It is recommended to use BigDecimal to ensure precision while arithmetic operations.
More information can be found at this post

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

Missing Format Argument Exception

When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.

Java - how to make these methods multithreaded? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Current code is single-threaded. It reads data from file, generate random numbers and check if that numbers belong to given interval.
import java.io.*;
import java.util.*;
class Generator {
private double mean;
private double variance;
private long amountOfNumbersToGenerate;
public Generator(double mean, double variance, long amountOfNumbersToGenerate) {
this.mean = mean;
this.variance = variance;
this.amountOfNumbersToGenerate = amountOfNumbersToGenerate;
}
double getMean() {
return mean;
}
double getVariance() {
return variance;
}
long getAmountOfNumbersToGenerate() {
return amountOfNumbersToGenerate;
}
}
class Interval {
private double start;
private double end;
public Interval(double start, double end) {
this.start = start;
this.end = end;
}
double getStart() {
return start;
}
double getEnd() {
return end;
}
}
class ParsedData {
private Vector<Generator> generators;
private Vector<Interval> intervals;
public ParsedData(Vector<Generator> generators, Vector<Interval> intervals) {
this.generators = generators;
this.intervals = intervals;
}
Vector<Generator> getGenerators() {
return generators;
}
Vector<Interval> getIntervals() {
return intervals;
}
}
class Worker extends Thread {
public Worker() {
}
}
class Start {
static ParsedData readDataFromFile(String path) throws IOException {
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
String delimiter = "\\s+";
// generators
long generatorSize = Long.parseLong(line);
Vector<Generator> generators = new Vector<Generator>();
for(long i =0; i < generatorSize; i++) {
line = br.readLine();
Scanner f = new Scanner(line);
f.useLocale(Locale.US); //without this line the program wouldn't work on machines with different locales
f.useDelimiter(delimiter);
Generator g = new Generator(f.nextDouble(), f.nextDouble(), f.nextInt());
generators.add(g);
}
line = br.readLine();
long intervalSize = Long.parseLong(line);
Vector<Interval> intervals = new Vector<Interval>();
for(long i = 0; i < intervalSize; i++) {
line = br.readLine();
System.out.println(line);
Scanner f = new Scanner(line);
f.useLocale(Locale.US); //without this line the program wouldn't work on machines with different locales
f.useDelimiter(delimiter);
Interval interval = new Interval(f.nextDouble(), f.nextDouble());
intervals.add(interval);
}
br.close();
return new ParsedData(generators, intervals);
}
static double boxMullerMarsagliaPolarRand(double mean, double variance) {
double micro = mean;
double sigma = Math.sqrt(variance);
double y, x, omega;
Random random = new Random();
do {
x = random.nextDouble();
y = random.nextDouble();
omega = x * x + y * y;
} while (!(0.0 < omega && omega < 1.0));
double sigma_sqrt = sigma * Math.sqrt(-2.0 * Math.log(omega) / omega);
double g = micro + x * sigma_sqrt;
// float h = micro + y * sigma_sqrt;
return g;
}
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static Vector<Double> generateRandomNumbers(ParsedData parsedData) {
Vector<Double> generatedNumbers = new Vector<Double>();
for(int i = 0; i < parsedData.getGenerators().size(); i++) {
Generator g = parsedData.getGenerators().get(i);
for(long j = 0; j < g.getAmountOfNumbersToGenerate(); j++) {
double random = boxMullerMarsagliaPolarRand(g.getMean(), g.getVariance());
generatedNumbers.add(random);
}
}
return generatedNumbers;
}
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static int[] checkIntervals(ParsedData parsedData, Vector<Double> generatedNumbers) {
int[] numberOfHits = new int[parsedData.getIntervals().size()];
for(int j = 0; j < parsedData.getIntervals().size(); j++) {
Interval interval = parsedData.getIntervals().get(j);
for(int i = 0; i < generatedNumbers.size(); i++) {
if (interval.getStart() < generatedNumbers.get(i) && generatedNumbers.get(i) < interval.getEnd()) {
numberOfHits[j]++;
}
}
}
return numberOfHits;
}
public static void main(String args[]) {
int amountOfThreads = Integer.parseInt(args[0]);
String path = System.getProperty("user.dir") + "/input.dat";
ParsedData parsedData = null;
try {
parsedData = readDataFromFile(path);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(parsedData.getGenerators().size());
System.out.println(parsedData.getIntervals().size());
Vector<Double> generatedNumbers = generateRandomNumbers(parsedData);
int[] numberOfHits = checkIntervals(parsedData, generatedNumbers);
for (int i = 0; i < numberOfHits.length; i++) {
Interval interval = parsedData.getIntervals().get(i);
System.out.println("" + (i+1) + " " + interval.getStart() + " " + interval.getEnd() + " " + numberOfHits[i]);
}
System.out.println(generatedNumbers.size());
}
}
I don't expect for anyone to write/refactor code for me.
But I don't know how to make this methods multi-threaded:
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static Vector<Double> generateRandomNumbers(ParsedData parsedData) {
Vector<Double> generatedNumbers = new Vector<Double>();
for(int i = 0; i < parsedData.getGenerators().size(); i++) {
Generator g = parsedData.getGenerators().get(i);
for(long j = 0; j < g.getAmountOfNumbersToGenerate(); j++) {
double random = boxMullerMarsagliaPolarRand(g.getMean(), g.getVariance());
generatedNumbers.add(random);
}
}
return generatedNumbers;
}
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static int[] checkIntervals(ParsedData parsedData, Vector<Double> generatedNumbers) {
int[] numberOfHits = new int[parsedData.getIntervals().size()];
for(int j = 0; j < parsedData.getIntervals().size(); j++) {
Interval interval = parsedData.getIntervals().get(j);
for(int i = 0; i < generatedNumbers.size(); i++) {
if (interval.getStart() < generatedNumbers.get(i) && generatedNumbers.get(i) < interval.getEnd()) {
numberOfHits[j]++;
}
}
}
return numberOfHits;
}
The easiest way to make this multithreaded is to use a producer-consumer pattern, with one producer reading the data and sending it to a BlockingQueue, and the consumers reading the data from the BlockingQueue (using take) and processing it using your two static methods. This way you need to do minimal refactoring - the static methods are already re-entrant / thread-safe (assuming that the Vector and ParsedData parameters aren't shared), so they don't need to be modified at all.

Java - NullPointerException in a method

I'm writing a program that could manage universitary students with courses and subjects. The problem of the class I'm showing you is that when the method
public CorsoStudi(String unNomeCorso, ArrayList unElencoMaterie, int unIdCorso)
is called it throws a NullPointerException at line elencoEsamiDati.add(q);. So, probably the problem is with this line and the line after this:
EsameDato q = new EsameDato(unElencoMaterie.get(contatore), 0);
Eclipse doesn't advice error on writing code.
Creatore.java
import java.util.ArrayList;
import java.util.Scanner;
public class Creatore {
int counterStudenti = 0;
int counterMaterie = 0;
int counterCorsi = 0;
//int counterEsami = 0;
ArrayList<Studente> listaStudenti = new ArrayList<Studente>();
ArrayList<Materia> listaMaterie = new ArrayList<Materia>();
ArrayList<CorsoStudi> listaCorsi = new ArrayList<CorsoStudi>();
//ArrayList<EsameDato> listaEsami = new ArrayList<EsameDato>();
public void iscriviStudente(String nomeStudente, String cognomeStudente, CorsoStudi corsoStudente){
listaStudenti.add(new Studente(nomeStudente, cognomeStudente, counterStudenti, corsoStudente));
counterStudenti++;
}
public void reimmatricolaStudente(int unaMatricola, int unIdCorso){
int c = 0;
CorsoStudi unCorso = null;
for(c = 0; c < listaCorsi.size(); c++){
if(listaCorsi.get(c).getIdCorso() == unIdCorso)
unCorso = listaCorsi.get(c);
}
int contatore = 0;
for(contatore = 0; contatore < listaStudenti.size(); contatore++)
if(listaStudenti.get(contatore).getMatricola() == unaMatricola){
iscriviStudente(listaStudenti.get(contatore).getNome(), listaStudenti.get(contatore).getCognome(), unCorso);
rimuoviStudente(unaMatricola);
};
}
public void rimuoviStudente(int matricola){
int contatore;
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getMatricola() == matricola)
listaStudenti.remove(contatore);
}
}
public Materia creaMateria(String nomeMateria, int crediti){
listaMaterie.add(new Materia( nomeMateria, crediti, counterMaterie));
counterMaterie++;
return listaMaterie.get(counterMaterie - 1);
}
public void creaCorsoStudi(String nomeCorso, ArrayList<Materia> materieCorso){
CorsoStudi q = new CorsoStudi( nomeCorso, materieCorso, counterCorsi);
listaCorsi.add(q);
counterCorsi++;
}
public ArrayList<Studente> cercaStudente(int opzione, String pattern){
int contatore = 0;
ArrayList<Studente> listaRicercati = new ArrayList<Studente>();
//opzione 1 = ricerca per nome
if(opzione == 1)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getNome().equalsIgnoreCase(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
//opzione 2 = ricerca per cognome
if(opzione == 2)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getCognome().equalsIgnoreCase(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
//opzione 3 = ricerca per matricola
if(opzione == 3)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getMatricola() == Integer.parseInt(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
//opzione 4 = ricerca per corsoStudi
if(opzione == 4)
for(contatore = 0; contatore < listaStudenti.size(); contatore++){
if(listaStudenti.get(contatore).getCorsoStudi().getIdCorso() == Integer.parseInt(pattern))
listaRicercati.add(listaStudenti.get(contatore));
};
return listaRicercati;
}
public Materia materiaDaId(int id){
int c = 0;
Materia materiaDaRitornare = null;
for(c = 0; c < listaMaterie.size(); c++){
if(listaMaterie.get(c).getIdMateria() == id)
materiaDaRitornare = listaMaterie.get(c);
}
return materiaDaRitornare;
}
}
CorsoStudi.java
import java.util.ArrayList;
import java.util.Scanner;
public class CorsoStudi {
private String nomeCorso;
private int idCorso;
private ArrayList<Materia> elencoMaterie;
private ArrayList<EsameDato> elencoEsamiDati;
public CorsoStudi(String unNomeCorso, ArrayList<Materia> unElencoMaterie, int unIdCorso){
nomeCorso = unNomeCorso;
elencoMaterie = unElencoMaterie;
idCorso = unIdCorso;
int contatore = 0;
//EsameDato q = null;
for(contatore = 0; contatore < unElencoMaterie.size(); contatore++){
EsameDato q = new EsameDato(unElencoMaterie.get(contatore), 0);
elencoEsamiDati.add(q);
};
}
public String getNomeCorso(){
return nomeCorso;
}
public int getIdCorso(){
return idCorso;
}
public ArrayList<Materia> getElencoMaterie(){
return elencoMaterie;
}
public ArrayList<EsameDato> getElencoEsamiDati(){
return elencoEsamiDati;
}
public String toString(){
String s = "";
s = s + "Ecco le materie di questo Corso di Studi:\n";
int c = 0;
for(c= 0; c < elencoMaterie.size(); c++){
s = s + elencoMaterie.get(c).getIdMateria() + " ";
s = s + elencoMaterie.get(c).getNomeMateria() + " (";
s = s + elencoMaterie.get(c).getCrediti() + " crediti)\n";
}
return s;
}
}
You have not initialized the field elencoEsamiDati therefore the actual value is null.
Before adding elements to an ArrayList you need to create it:
private ArrayList<EsameDato> elencoEsamiDati = new ArrayList<EsameDato>();
You may also need to initialize other fields as well.
BTW it is not a good idea to use your own language when programming, use English instead.

getting rid of java nullpointerexception and arrayindexoutofbound exception

im getting these exceptions on random occurrences. Sometimes they occur.Sometimes they dont
Please run this code and help me in getting rid of them
package my.matcher;
//import java.util.Calendar;
public class Matcher {
/*public static class priceHeap{
int price;
int orderid;
int quantity;
priceHeap(){
price = 0;
orderid = 0;
quantity = 0;
}
}*/
//private int price;
//private int type;
public static class PriceNode{
int price;
int logid;
public PriceNode(){
}
}
PriceNode[] buyPriceHeap = new PriceNode[maxHeapSize];
PriceNode[] sellPriceHeap = new PriceNode[maxHeapSize];
public static int temp_logid = 0;
public static int orderNum=0;
public static int tradeNum=0;
public static int buyOrderNum=0;
public static int sellOrderNum=0;
public static int totalOrders=0;
public static int checkMatchReturn=2;
public static final int maxHeapSize = 40000;
//public static int[] sellPriceHeap = new int[maxHeapSize];
//public static int[] buyPriceHeap = new int[maxHeapSize];
public static int buyHeapSize = 0;
public static int sellHeapSize = 0;
public static class Order{
int orderid;
int price;
int quantity;
int logid;
Order(){
orderid = 0;
price = 0;
quantity = 0;
logid = 0;
}
}
public static final int maxOrders = 100;
public static int buyOrderArraySize = 0;
public static int sellOrderArraySize = 0;
Order[] buyOrderArray = new Order[maxOrders];
Order[] sellOrderArray = new Order[maxOrders];
public void siftUpMax(int child){
int parent , tmp1,tmp2;
if(child != 0){
parent = (child-1)/2;
if(buyPriceHeap[parent].price < buyPriceHeap[child].price){
tmp1 = buyPriceHeap[parent].price;
tmp2 = buyPriceHeap[parent].logid;
buyPriceHeap[parent].price = buyPriceHeap[child].price;
buyPriceHeap[parent].logid = buyPriceHeap[child].logid;
buyPriceHeap[child].price = tmp1;
buyPriceHeap[child].logid = tmp2;
siftUpMax(parent);
}
}
}
public void siftUpmin(int child){
int parent , tmp1,tmp2;
if(child != 0){
parent = (child-1)/2;
if(sellPriceHeap[parent].price > sellPriceHeap[child].price){
tmp1 = sellPriceHeap[parent].price;
tmp2 = sellPriceHeap[parent].logid;
sellPriceHeap[parent].price = sellPriceHeap[child].price;
sellPriceHeap[parent].logid = sellPriceHeap[child].logid;
sellPriceHeap[child].price = tmp1;
sellPriceHeap[child].logid = tmp2;
siftUpmin(parent);
}
}
}
public void buyPriceHeapInsert(int num , int id){
if(buyHeapSize == buyPriceHeap.length){
System.out.println("OVerflow");
}
else{
buyHeapSize++;
buyPriceHeap[buyHeapSize-1] = new PriceNode();
buyPriceHeap[buyHeapSize-1].price = num;
buyPriceHeap[buyHeapSize-1].logid = id;
siftUpMax(buyHeapSize-1);
}
return;
}
public void sellPriceHeapInsert(int num , int id){
if(sellHeapSize == sellPriceHeap.length){
System.out.println("OverFlow");
}
else{
sellHeapSize++;
sellPriceHeap[sellHeapSize-1] = new PriceNode();
sellPriceHeap[sellHeapSize-1].price = num;
sellPriceHeap[sellHeapSize-1].logid = id;
siftUpmin(sellHeapSize-1);
}
return;
}
public void buyPriceHeapDelete(){
//int temp = buyPriceHeap[0];
buyPriceHeap[0].logid = buyPriceHeap[buyHeapSize-1].logid;
buyPriceHeap[0].price = buyPriceHeap[buyHeapSize-1].price;
buyHeapSize--;
if(buyHeapSize > 0){
siftDownMax(0);
}
}//Need to find a better way to delete from heap in java.
public void siftDownMax(int parent){
int left,right,max,tmp1,tmp2;
left = (2*parent) + 1;
right = (2*parent) + 2;
if(right >= buyHeapSize){
if(left >= buyHeapSize)
return;
else
max = left;
}
else{
if(sellPriceHeap[left].price >= sellPriceHeap[right].price)
max = left ;
else
max = right;
}
if(sellPriceHeap[parent].price < sellPriceHeap[max].price){
tmp1 = sellPriceHeap[parent].logid;
tmp2 = sellPriceHeap[parent].price;
sellPriceHeap[parent].logid = sellPriceHeap[max].logid;
sellPriceHeap[parent].price = sellPriceHeap[max].price;
sellPriceHeap[max].logid = tmp1;
sellPriceHeap[max].price = tmp2;
siftDownMin(max);
}
}
public void sellPriceHeapDelete(){
//int temp = sellPriceHeap[0];
sellPriceHeap[0].logid = sellPriceHeap[sellHeapSize-1].logid;
sellPriceHeap[0].price = sellPriceHeap[sellHeapSize-1].price;
sellHeapSize--;
if(sellHeapSize > 0){
siftDownMin(0);
}
}
public void siftDownMin(int parent){
int left,right,min,tmp1,tmp2;
left = (2*parent) + 1;
right = (2*parent) + 2;
if(right >= sellHeapSize){
if(left >= sellHeapSize)
return;
else
min = left;
}
else{
if(sellPriceHeap[left].price <= sellPriceHeap[right].price)
min = left ;
else
min = right;
}
if(sellPriceHeap[parent].price > sellPriceHeap[min].price){
tmp1 = sellPriceHeap[parent].logid;
tmp2 = sellPriceHeap[parent].price;
sellPriceHeap[parent].logid = sellPriceHeap[min].logid;
sellPriceHeap[parent].price = sellPriceHeap[min].price;
sellPriceHeap[min].logid = tmp1;
sellPriceHeap[min].price = tmp2;
siftDownMin(min);
}
}
public int buyPriceHeapMax(){
int maxBuy = 0;
for(int i=0;i<buyHeapSize;i++){
maxBuy = buyPriceHeap[0].price;
if(buyPriceHeap[i].price>maxBuy){
maxBuy = buyPriceHeap[i].price;
}
}
return maxBuy;
}
public int sellPriceHeapMin(){
int minSell = 0;
for(int i=0;i<sellHeapSize;i++){
minSell = sellPriceHeap[0].price;
if(sellPriceHeap[i].price<minSell){
minSell = sellPriceHeap[i].price;
}
}
return minSell;
}
/*public void setPrice(int p){
price = p;
}
public void setType(int t){
type = t;
}
*/
/* public void checkType(int t){
if(t==1){
System.out.println("Buy Order");
}
else{
System.out.println("Sell Order");
}
}*/
public void checkMatch(int p,int t,int q,int id){
if(t==1){//Buy
buyOrderNum++;
if(sellPriceHeap[0].price != 0 && sellPriceHeap[0].price < p){
tradeNum++;
int log_id = sellPriceHeap[0].logid;
//System.out.println("The active Buy Order has been matched with a Sell Order");
//System.out.println("Buy Order Price : " + p);
//int x = sellPriceHeapMin();
//System.out.println("Sell Order Price : " + x);
quantityCheck(p,q,t,id,log_id);
//System.out.println("Both the entries have been Removed from the storage");
//System.out.println("Now We Move On to the next Entry");
checkMatchReturn=1;
return;
}
else{
checkMatchReturn=2;
}
}
else if(t==2){//Sell
sellOrderNum++;
if(buyPriceHeap[0].price!=0 && buyPriceHeap[0].price > p){
int log_id = buyPriceHeap[0].logid;
tradeNum++;
//System.out.println("The active Sell Order has been matched with a Buy Order");
//System.out.println("Sell Order Price : " + p);
//int y = buyPriceHeapMax();
//System.out.println("Buy Order Price : " +y);
quantityCheck(p,q,t,id,log_id);
//System.out.println("Both the entries have been Removed from the storage");
//System.out.println("Now We Move On to the next Entry");
checkMatchReturn=1;
return;
}
else{
checkMatchReturn=2;
}
}
return;
}
public void buyOrderArrayInsert(int id,int p,int q){
buyOrderArraySize++;
int i = buyOrderArraySize-1;
buyOrderArray[i] = new Order();
buyOrderArray[i].orderid = id;
buyOrderArray[i].price = p;
buyOrderArray[i].quantity = q;
temp_logid = i;
//int index = Arrays.binarySearch(buyPriceHeap, i);
}
public void sellOrderArrayInsert(int id,int p,int q){
sellOrderArraySize++;
int i = sellOrderArraySize-1;
sellOrderArray[i] = new Order();
sellOrderArray[i].orderid = id;
sellOrderArray[i].price = p;
sellOrderArray[i].quantity = q;
temp_logid = i;
}
public void quantityCheck(int p,int qty,int t,int id , int lid){
int match = 0;
if(t==1){
match = lid;
int qmatch = sellOrderArray[match].quantity;
if(qmatch == qty){
sellPriceHeapDelete();
//System.out.println("Quantities of Both Matched Entries were same");
//System.out.println("Both Entries Removed");
return;
}
else if(qty < qmatch){
int temp = qmatch - qty;
sellOrderArray[match].quantity=temp;
//System.out.println("The Active Buy Order Has been Removed");
//System.out.println("The Passive Sell Order Has Been Updated");
return;
}
else if(qty > qmatch){
int temp = qty - qmatch;
sellPriceHeapDelete();
//System.out.println("The Passive Sell Order Has Been Removed");
buyOrderArrayInsert(id,p,temp);
//System.out.println("The Active Buy Order Has Been Updated and Added");
buyPriceHeapInsert(p,temp_logid);
removeSellOrder(match);
return;
}
}
else if(t==2){
//Active is Sell Order
match = lid;
int qmatch = buyOrderArray[match].quantity;
if(qmatch == qty){
buyPriceHeapDelete();
//System.out.println("Quantities of Both Matched Entries were same");
//System.out.println("Both Entries Removed");
return;
}
else if(qty < qmatch){
int temp = qmatch - qty;
buyOrderArray[match].quantity=temp;
//System.out.println("The Active Sell Order Has been Removed");
//System.out.println("The Passive Buy Order Has Been Updated");
return;
}
else if(qty > qmatch){
int temp = qty - qmatch;
buyPriceHeapDelete();
//System.out.println("The Passive Sell Order Has Been Removed");
sellOrderArrayInsert(id,p,temp);
//System.out.println("The Active Buy Order Has Been Updated and Added");
sellPriceHeapInsert(p,temp_logid);
removeBuyOrder(match);
return;
}
}
}
public void removeSellOrder(int n){
sellOrderArray[n].orderid=0;
sellOrderArray[n].price=0;
sellOrderArray[n].quantity=0;
if(n < sellOrderArraySize - 1){
for(int i=n+1;i<sellOrderArraySize;i++){
int tempid = sellOrderArray[i-1].orderid;
int tempprice = sellOrderArray[i-1].price;
int tempqty = sellOrderArray[i-1].quantity;
sellOrderArray[i-1].orderid=sellOrderArray[i].orderid;
sellOrderArray[i-1].quantity=sellOrderArray[i].quantity;
sellOrderArray[i-1].price=sellOrderArray[i].price;
sellOrderArray[i].orderid = tempid;
sellOrderArray[i].price = tempprice;
sellOrderArray[i].quantity = tempqty;
}
}
}
public void removeBuyOrder(int n){
buyOrderArray[n].orderid=0;
buyOrderArray[n].price=0;
buyOrderArray[n].quantity=0;
if(n < buyOrderArraySize - 1){
for(int i=n+1;i<buyOrderArraySize;i++){
int tempid = buyOrderArray[i-1].orderid;
int tempprice = buyOrderArray[i-1].price;
int tempqty = buyOrderArray[i-1].quantity;
buyOrderArray[i-1].orderid=buyOrderArray[i].orderid;
buyOrderArray[i-1].quantity=buyOrderArray[i].quantity;
buyOrderArray[i-1].price=buyOrderArray[i].price;
buyOrderArray[i].orderid = tempid;
buyOrderArray[i].price = tempprice;
buyOrderArray[i].quantity = tempqty;
}
}
}
/*
void printBuyOrder(int[] a){
System.out.println("The Buy Order List is : ");
for(int i=0;i<buyOrderArraySize;i++){
System.out.println(" Order ID = " + buyOrderArray[i].orderid);
System.out.println(" Price = " + buyOrderArray[i].price);
System.out.println(" Quantity = " + buyOrderArray[i].quantity);
System.out.println("---------------------");
}
}*/
public static void main(String[] args){
int inprice=0,intype=0,inquantity=0,inorderid=0,x=0;
long startTime=0,endTime=0;
Matcher ob = new Matcher();
ob.buyPriceHeap[x] = new PriceNode();
ob.sellPriceHeap[x] = new PriceNode();
//Calendar now = Calendar.getInstance();
//int s1 = now.get(Calendar.SECOND);
startTime = System.nanoTime();
for (int i=0;i<maxOrders;i++){
inprice = (int) (Math.random() *500 +1 );
intype = (int) (Math.random() *2 +1);
inquantity = (int) (Math.random() *100 +1);
inorderid = i;
orderNum++;
//ob.setPrice(inprice);
//ob.setType(intype);
//System.out.println("orderid : "+ inorderid + " price : " +inprice + " type : " + intype + "quantity : " + inquantity);
ob.checkMatch(inprice,intype,inquantity,inorderid);
if(checkMatchReturn == 2){
//System.out.println("No Matching Order");
if(intype==1){
ob.buyOrderArrayInsert(inorderid, inprice, inquantity);
ob.buyPriceHeapInsert(inprice,temp_logid);
//System.out.println("The Unmatched Order is then inserted Into the Buy Order List");
}
if(intype==2){
ob.sellOrderArrayInsert(inorderid, inprice, inquantity);
ob.sellPriceHeapInsert(inprice,temp_logid);
//System.out.println("The Unmatched Order is then inserted Into the Sell Order List");
}
}
}
//int s2 = now.get(Calendar.SECOND);
/*System.out.println("The Pending Orders in the lists are : ");
System.out.println(" ~~~~~ Buy Order List ~~~~~ ");
for(int x=0;x<buyHeapSize;x++){
System.out.print(" "+ buyPriceHeap[x]);
}
System.out.println(" ~~~~~ Sell Order List ~~~~~ ");
for (int y=0;y<sellHeapSize;y++){
System.out.print(" " + sellPriceHeap[y]);
System.out.println("");
}*/
//int timetaken = s2-s1;
endTime = System.nanoTime();
long timetaken = endTime - startTime;
double timetakenS = ((double)timetaken)/1000000000;
System.out.println("Number of Orders = " +orderNum);
System.out.println("Number of Trades Generated = " +tradeNum);
System.out.println("Number of Buy Orders = " +buyOrderNum);
System.out.println("Number of Sell Orders = " +sellOrderNum);
System.out.println("Total Time Taken = " +timetakenS+" seconds");
double orderRate = ((double)(orderNum))/(timetakenS);
System.out.println("Order Rate = " +orderRate+" per second");
double avgTime = (timetakenS)/((double)(orderNum))*1000000;
System.out.println("Average Execution Time per Order = "+avgTime+" micro seconds");
//System.out.println("Do You Want to Print the Pending Order Books?");
//System.out.println("y/n?");
}
}
If you're getting an ArrayIndexOutOfBound exception on the line:
buyPriceHeap[0].logid = buyPriceHeap[buyHeapSize-1].logid;
then obviously you need to check the value of buyHeapSize. That should show you instantly what the problem is.
It'll either be some value higher than the actual size of the array or it will be zero. In the former case, it's probably because you're not keeping it in sync with the actual array. In the latter, you're probably trying to delete from an empty heap.
Those are the likely causes which you should investigate. The question is of limited value to others here so I'm wary of investing too much time other than to say you should either step through it with a debugger or pepper your code temporarily with System.out.println statements (general advice rather than a specific fix).
Both these options will make you a better person, debugging-wise.

Categories