JTable object [][] data - java

I am trying to create a table based on my trial class. When I try to run my table class the table prints with the proper heading, but it does not print anything in the body of the table. How should I fix my for loop so the data enters the table? Do I need to add a parameter to the constructor?
I understand there are more getters and setters than necessary. I was just trying to go about the for loop in different ways.
public class Trial extends JFrame{
static int counter = 0;
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
int lapsCount = 0;
String[] array1;
double[] array2;
double[] array3;
public int getLapsCount() {
return lapsCount;
}
public void setLapsCount(int lapsCount) {
this.lapsCount = lapsCount;
}
public static int getCounter() {
return counter;
}
public static void setCounter(int counter) {
Trial.counter = counter;
}
public int getLaps() {
return laps;
}
public void setLaps(int laps) {
this.laps = laps;
}
public String getLapTime() {
return lapTime;
}
public void setLapTime(String lapTime) {
this.lapTime = lapTime;
}
public double getCurrentTime() {
return currentTime;
}
public void setCurrentTime(double currentTime) {
this.currentTime = currentTime;
}
public String getDifference() {
return difference;
}
public void setDifference(String difference) {
this.difference = difference;
}
public String[] getArray1() {
return array1;
}
public void setArray1(String[] array1) {
this.array1 = array1;
}
public double[] getArray2() {
return array2;
}
public void setArray2(double[] array2) {
this.array2 = array2;
}
public double[] getArray3() {
return array3;
}
public void setArray3(double[] array3) {
this.array3 = array3;
}
public static void main(String[] args) {
//drop down for number of laps
String lapsString;
String[] selections = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
lapsString = (String) JOptionPane.showInputDialog(null,
"Choose a number of laps:",
"Lap Counter",
JOptionPane.INFORMATION_MESSAGE,
null, /* icon */
selections,
"0");
System.out.printf("Number of laps = \"%s\"\n", lapsString);
int lapsCount = Integer.parseInt(lapsString);
String[] array1 = new String[lapsCount+1];
double[] array2 = new double[lapsCount+1];
double[] array3 = new double[lapsCount+1];
// showInputDialog with for lap time
for (int i = 1; i <= lapsCount; i++){
String lapTime;
lapTime =
JOptionPane.showInputDialog("Enter lap " + i + " total time.");
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
array1[i] = lapTime;
double currentTime = inputConvert(array1[i]);
array2[i] = currentTime;
array3[i] = (array2[i] - array2[i-1]);
counter++;
//confirm each time
int result;
String[] results = { "Yes", "No", "Cancel" };
result = JOptionPane.showConfirmDialog(null,
"Please confirm lap " + i + " is " + lapTime);
if (result == -1)
System.out.printf("user closed window\n");
else if (result == 0)
System.out.printf("result = %d, user pressed \"%s\"\n", result, results[result]);
else {
lapTime =
JOptionPane.showInputDialog("Please re-enter lap " + i);
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
counter++;
}
}
}
public static double inputConvert(String s) {
double convert = 0.0;
int minutes = Integer.parseInt(s.substring(0, 1));
double seconds = Double.parseDouble(s.substring(2, s.length()));
minutes = minutes * 60;
convert = minutes + seconds;
return convert;
}
private static String getDifference(int j, double sign) {
String difference = "";
if(j == 0) {
difference = "---";
}
else if(sign > 0.0) {
difference = "+";
}
return difference;
}
public static String displayTime(double time) {
String result = null;
int minutes = (int) (time/60);
double seconds = (time % 60);
seconds = Math.round(seconds*100.0)/100.0;
if(seconds < 10){
result = minutes + ":0" + seconds;
}
else{
result = minutes + ":" + seconds;
}
return result;
}
}
This is my table class where the problem arises.
public class table {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new table();
}
});
}
public table() {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Table to record lap times");
guiFrame.setSize(700,200);
guiFrame.setLocationRelativeTo(null);
JTable table = new JTable(new ExampleTableModel());
table.setAutoCreateRowSorter(true);
table.setGridColor(Color.YELLOW);
table.setBackground(Color.CYAN);
JScrollPane tableScrollPane = new JScrollPane(table);
guiFrame.add(tableScrollPane);
guiFrame.setVisible(true);
}
class ExampleTableModel extends AbstractTableModel{
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
Trial t = new Trial();
//Two arrays used for the table data
private String[] columnNames = {"Lap #", "Total Time", "Lap Time" , "Difference" };
private Object[][] data;
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1() [i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
#Override public int getRowCount() {
return data.length;
}
#Override public int getColumnCount() {
return columnNames.length;
}
#Override public Object getValueAt(int row, int column) {
return data[row][column];
}
#Override public String getColumnName(int column) {
return columnNames[column];
}
#Override public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override public boolean isCellEditable(int row, int column) {
if (column == 0 || column == 1) {
return false;
}
else {
return true;
}
}
}
}
I made those changes but I need my output to look like this
Lap #: Total time Lap time Difference
Lap1: 2:10 2:10 ---
I fixed the lap number so it starts at 1. I made these changes in the hopes that it would fix the lap time and difference cells but it is giving me an error.
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
if (i == 0){
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.getArray2() [i + 1];
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i]));
}
else {
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.displayTime(trial.getArray2() [i + 1] - trial.getArray2() [i]);
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i])) + (trial.getArray3()[i + 1] - trial.getArray3()[i]);
}
}
}

Edit: combining the code from the Trial.main and the Table.main methods
To make the code from your Trial class easier to use from the Table class, you can make the following changes. This way you can create a Trial object and call the getUserInput to let the user initialize it:
public static void main(String[] args) {
new Trial().getUserInput();
}
public void getUserInput() {
// [Code from the old main method...]
// Use the fields of the class instead of local variables:
lapsCount = Integer.parseInt(lapsString);
array1 = new String[lapsCount+1];
array2 = new double[lapsCount+1];
array3 = new double[lapsCount+1];
// [Code from the old main method...]
}
Now you can modify the Table model like this:
public Table() {
// [...]
Trial trial = new Trial();
trial.getUserInput();
JTable table = new JTable(new ExampleTableModel(trial));
// [...]
}
And let the ExampleTableModel constructor use a trail parameter (the laps and t fields are no longer used):
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = trial.getArray1()[i];
data[i][2] = trial.getArray2()[i];
data[i][3] = trial.getArray3()[i];
}
}
There was also an issue with the getColumnClass method:
#Override public Class getColumnClass(int column) {
//return getValueAt(0, column).getClass();
return (column <= 1) ? String.class : Double.class;
}
Now the table looks like this:
The output was:
Number of laps = "2"
Lap 1 = "2:10"
result = 0, user pressed "Yes"
Lap 2 = "2:20"
result = 0, user pressed "Yes"
Old answer
There seem to be a few issues that prevent the table from being filled:
In the ExampleTableModel class the laps field should be something higher than zero (for the constructor to fill the data array):
class ExampleTableModel extends AbstractTableModel {
//int laps = 0;
int laps = 6;
In the constructor of the ExampleTableModel class:
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1()[i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
the calls to the t.getArray1, t.getArray2, and t.getArray3 methods return null. The Trial object appears to have no data yet.
Do you want your program to execute both the code of the Trial.main method and the Table.main method?

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());
}
}

How to use array of objects in this context?

Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}

Get ranks to iterating ArrayList value

I have five values in an ArrayList like {50,25,50,30,10} . I want to set ranks in every value, So please tell me how I could do this. The output is like
50->1st rank
50->1st rank
30->2nd rank
20->3rd rank
10->4th rank
you should check this and this.
It is easy to do with lambda expression which is available from java 1.8.
Here is code i have got from above reference link
List<Player> players = new ArrayList<Player>() {{
add(new Player(1L, "a", 5));
add(new Player(2L, "b", 7));
add(new Player(3L, "c", 8));
add(new Player(4L, "d", 9));
add(new Player(5L, "e", 3));
add(new Player(6L, "f", 8));
}};
int[] score = {Integer.MIN_VALUE};
int[] no = {0};
int[] rank = {0};
List<Ranking> ranking = players.stream()
.sorted((a, b) -> b.getScores() - a.getScores())
.map(p -> {
++no[0];
if (score[0] != p.getScores()) rank[0] = no[0];
return new Ranking(rank[0], score[0] = p.getScores());
})
// .distinct() // if you want to remove duplicate rankings.
.collect(Collectors.toList());
System.out.println(ranking);
// result:
// rank=1, score=9
// rank=2, score=8
// rank=2, score=8
// rank=4, score=7
// rank=5, score=5
// rank=6, score=3
Please try this code.
package snakePack;
import java.util.ArrayList;
public class MainSnake {
public static void main(String[] args) {
Snake blackMambo = new Snake("blackMambo",2,0);
Snake rattle = new Snake("rattle",9,0);
Snake green = new Snake("green",6,0);
Snake cobra = new Snake("cobra",78,0);
Snake kingCobra = new Snake("kingCobra",5,0);
Snake whiteCobra = new Snake("whiteCobra",5,0);
Snake python = new Snake("python",5,0);
Snake yellow = new Snake("yellow",5,0);
Snake blackCobra = new Snake("blackCobra",1000,0);
Snake desertCobra = new Snake("desertCobra",5,0);
ArrayList<Snake> list = new ArrayList<Snake>();
list.add(blackMambo);list.add(rattle);list.add(green);list.add(cobra);list.add(kingCobra);
list.add(whiteCobra);list.add(python);list.add(yellow);list.add(blackCobra);list.add(desertCobra);
ArrayList<Integer> mongoosebigSnakes = new ArrayList<Integer>();
Integer tempHelperFrog = 0;
Integer rankMe = 0;
for (int grossHopper = 0; grossHopper < list.size(); grossHopper++) {
Integer strongSnake = 0;
for (int spider = 0; spider < list.size(); spider++) {
if (list.get(spider).getSnakePoisionRate() > strongSnake) {
boolean bool = false;
if (mongoosebigSnakes.size() != 0) {
for (int dragonFly = 0; dragonFly < mongoosebigSnakes.size(); dragonFly++) {
if (mongoosebigSnakes.get(dragonFly).intValue() == list.get(spider).getSnakePoisionRate().intValue()) {
bool = true;
}
}
if (bool != true) {
bool = false;
strongSnake = list.get(spider).getSnakePoisionRate();
}
} else {
if (tempHelperFrog != list.get(spider).getSnakePoisionRate()) {
strongSnake = list.get(spider).getSnakePoisionRate();
}
}
}
}
tempHelperFrog = strongSnake;
mongoosebigSnakes.add(strongSnake);
++rankMe;
for (int x = 0; x < list.size(); x++) {
if (strongSnake == list.get(x).getSnakePoisionRate()) {
list.get(x).setSnakeRank(rankMe);
}
}
}
System.out.println(" Hey guys get ready to see who has strong poison >>>");
Integer ratHelperCounter = 0;
for (Snake snake : list) {
System.out.println(++ratHelperCounter + " :" + snake.toString());
}
System.out.println("it's awesome" + " huge me !!!! ");
}
}
Bean class:
package snakePack;
public class Snake {
String snakeName;
Integer snakePoisionRate;
Integer snakeRank;
public Snake(String string, int i, int j) {
this.snakeName = "";
this.snakePoisionRate = i;
this.snakeRank = j;
}
public String getSnakeName() {
return snakeName;
}
public void setSnakeName(String snakeName) {
this.snakeName = snakeName;
}
public Integer getSnakePoisionRate() {
return snakePoisionRate;
}
public void setSnakePoisionRate(Integer snakePoisionRate) {
this.snakePoisionRate = snakePoisionRate;
}
public Integer getSnakeRank() {
return snakeRank;
}
public void setSnakeRank(Integer snakeRank) {
this.snakeRank = snakeRank;
}
#Override
public String toString() {
return "Snake [snakeName=" + snakeName + ", snakePoisionRate="
+ snakePoisionRate + ", snakeRank=" + snakeRank + "]";
}
}

Methods to display different table content, repeating header issue

I need to be able to use different methods in order to print out certain table content such as a sum, multiplication, or random table to name a few. I cannot figure out how to print out this content separate from the row ID. another problem I am having is when I enter "f" to reprint the table the header gets repeated each time I print it which just creates a very long repeating header after a few reprints, could someone help with this?
The original code will be followed by the IntTable class, it is not completely filled out which I am aware of but I want to figure this out before I move on.
import java.util.Scanner;
public class Assignment6{
public static String returnMenu(){
String menu = "Command Options---------------\na: Create a new table\nb: Change the row sizes\nc: Change the column sizes\nd: Change the data types\ne: Chnge the formats\nf: Display the table\ng: Display the log data\n:?: Display this menu\nq: Quit the program\n------------------------------";
return menu;
}
public static void main(String[] arg){
Scanner scan = new Scanner(System.in);
String input = "p";
String output = "NOOOOO!";
IntTable myTable = new IntTable();
while (!input.equals("q")){
System.out.println("Please input a command: ");
input = scan.nextLine();
if (input.equals("a")){
System.out.print("a [Input three integers to initialize table]: ");
myTable.setRow(scan.nextInt()); myTable.setColumn(scan.nextInt()); myTable.setType(scan.nextInt());
scan.nextLine();
myTable.printTable();
}
else if (input.equals("b")){
System.out.print("b [Enter integer to update table row]: ");
myTable.setRow(scan.nextInt());
scan.nextLine();
}
else if (input.equals("c")){
System.out.println("c [Enter integer to update column]: ");
myTable.setColumn(scan.nextInt());
scan.nextLine();
}
else if (input.equals("d")){
System.out.println("d [Enter integer to update data type]: ");
myTable.setType(scan.nextInt());
scan.nextLine();
}
else if (input.equals("e")){
System.out.println("e [Enter integer to update printf format]: ");
}
else if (input.equals("f")){
System.out.println("f [Display table]: ");
myTable.printTable();
}
else if (input.equals("g")){
System.out.println("g [Display data log]: ");
}
else if (input.equals("?")){
System.out.println(Assignment6.returnMenu());
}
else
System.out.println("Invalid: ***Type \"?\" to get the commands***");
}
}
}
public class IntTable{
private int row, column, type;
static String log, tFormat;
final int TYPE_DEFAULT = 0;
final int TYPE_NUMBERS = 1;
final int TYPE_SUM = 2;
final int TYPE_MULTIPLY = 3;
final int TYPE_RANDOM = 4;
final int TYPE_POWER = 5;
final int TYPE_FIBONACCI = 6;
String beginRow = " * |";
String divider = "-------";
int count = 1;
public IntTable(){
}
public IntTable(int row, int column, int type){
}
public int getRow(){
return row;
}
public int getColumn(){
return column;
}
public int getType(){
return type;
}
public void setRow(int newRow){
row = newRow;
}
public void setColumn(int newColumn){
column = newColumn;
}
public void setType(int newType){
type = newType;
}
public void printTable(){
int count = 1;
printTableHeader();
for(int i = 1; i <row+1; i++){
System.out.printf("%4d %4s", i, " |");
for (int j = 1; j < column+1; j++)
{
System.out.printf("%4d", count);
count++;
}
System.out.println();
}
}
private void printTableHeader(){
for(int i = 1; i < column + 1; i++)
{
beginRow+=" "+i;
divider+="-----";
}
System.out.println(beginRow);
System.out.println(divider);
}
private void printTableRowID(int ID){
ID = row;
for(int i = 1; i <ID+1; i++){
System.out.printf("%4d %4s", i, " |");
System.out.print(getElement(i, (row-(row-1))));
System.out.println();
}
}
private int getElement(int c, int r){
if(type == 0)
return 0;
else if(type == 1)
return c+column;
else if(type == 2)
return c+ r;
else if(type == 3)
return c*r;
else if(type == 4)
return (int)(1 + Math.random()*10);
else if(type == 5)
return (int)Math.pow(r, c);
else
return r;
}
private int pow(int one, int two){
return (int)Math.pow(one, two);
}
private int fibonacci(int fib){
return fib;
}
private int sum(int add, int addd){
return add + addd;
}
private int multiply(int prod, int product){
return prod * product;
}
private int random(int what, int huh){
return (int)(what + Math.random()*huh);
}
}
the reason why header repeating is because you do not reinitialize variable(beginRow and divider)
when you call printTable Method, variable String beginRow = " * |"; String divider = "-------"; is redefined
you need to reintialize variable(beginRow, divider)
look fllowing code which i modified
private void printTableHeader()
{
for(int i = 1; i < column + 1; i++)
{
beginRow+=" "+i;
divider+="-----";
}
System.out.println(beginRow);
System.out.println(divider);
beginRow = " * |";
divider = "-------";
}

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