Methods to display different table content, repeating header issue - java

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 = "-------";
}

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 place a number in every position my horse pawn has been to (in a 2D "board" array)

The program basically prompts the user to pick one of the displayed moves and move the horse pawn in the chess board. Ιn this way we try to see how many times the horse can move to the chessboard without being out of bounds or even in the same position.
The problem is that I haven't figured out a way to place a number (starting from 1) for the positions where the horse has been to. More specifically I want it to print H in the current position of the horse and 1 to ... on the past positions.
import java.util.Scanner;
public class Ex7_22 {
private static Scanner scanner = new Scanner(System.in);
private static String[][] board = new String[8][8];
private static int[] horizontal = new int[8];
private static int[] vertical = new int[8];
private static boolean[][] boardPositions = new boolean[8][8];
private static int currentRow = 3;
private static int currentColumn = 4;
public static void main(String[] args){
fillArrays();
boolean outOfBoundsV;
boolean outOfBoundsH;
boolean positionAvailability = false;
int VerticalMove,HorizontalMove;
fillBoard();
board[3][4] = "H";
boardPositions[3][4] = true;
displayBoard();
int pickMove;
for(int i=1;i<=64;i++){
displayBoardPositions();
displayPossibleMoves();
do {
System.out.println("\nPick one of the displayed moves to do (0-7): ");
pickMove = scanner.nextInt();
VerticalMove = moveHorse_Vertical(pickMove);
HorizontalMove = moveHorse_Horizontal(pickMove);
outOfBoundsV = checkForOutOfBounds(VerticalMove);
outOfBoundsH = checkForOutOfBounds(HorizontalMove);
if ((outOfBoundsV)||(outOfBoundsH)){
reverse(pickMove);
}
if((!outOfBoundsV)&&(!outOfBoundsH)){
positionAvailability = checkForPositionAvailability(VerticalMove,HorizontalMove);
if((!positionAvailability)){
reverse(pickMove);
}
}
}while (((outOfBoundsV)||(outOfBoundsH))||(!positionAvailability));
board[VerticalMove][HorizontalMove] = "H";
//placeNumber(VerticalMove,HorizontalMove,pickMove);
boardPositions[VerticalMove][HorizontalMove] = true;
displayBoard();
}
}
/* private static void placeNumber(int VerticalMove, int HorizontalMove, int pickMove) {
//have to place number in every position the horse has been to. Haven't managed to get it working.
reverse(pickMove);
int i=0;
i++;
String iStr = String.valueOf(i);
board[VerticalMove][HorizontalMove] = iStr;
currentRow += vertical[pickMove];
currentColumn += horizontal[pickMove];
} */
private static void reverse(int move){
currentRow -= vertical[move];
currentColumn -= horizontal[move];
}
private static void fillBoard(){
for(int i=0;i<board.length;i++){
for(int j=0;j<board[i].length;j++){
board[i][j] = "0";
}
}
}
private static boolean checkForPositionAvailability(int vertical, int
horizontal) {
if(!boardPositions[vertical][horizontal]){
return true;
}
else{
System.out.println("You've already been in this position.");
return false;
}
}
private static boolean checkForOutOfBounds(int position) {
if((position<0)||(position>=8)){
System.out.print("Position out of bounds\nPlease choose another move\n");
return true;
}
else return false;
}
private static int moveHorse_Vertical(int move) {
currentRow += vertical[move];
return currentRow;
}
private static int moveHorse_Horizontal(int move){
currentColumn += horizontal[move];
return currentColumn;
}
private static void fillArrays() {
//fill horizontal array
horizontal[0] = 2;
horizontal[1] = 1;
horizontal[2] = -1;
horizontal[3] = -2;
horizontal[4] = -2;
horizontal[5] = -1;
horizontal[6] = 1;
horizontal[7] = 2;
//fill vertical array
vertical[0] = -1;
vertical[1] = -2;
vertical[2] = -2;
vertical[3] = -1;
vertical[4] = 1;
vertical[5] = 2;
vertical[6] = 2;
vertical[7] = 1;
}
private static void displayBoard(){
System.out.print("\n");
System.out.println(" 0 1 2 3 4 5 6 7");
System.out.println(" ----------------------------- ");
for(int i=0;i<board.length;i++){
System.out.print(i + "|\t");
for(int j=0;j<board[i].length;j++){
System.out.print(" "+board[i][j] + "\t");
}
System.out.println();
}
}
private static void displayBoardPositions(){
System.out.print("\n");
System.out.println(" 0 1 2 3 4 5 6 7");
System.out.println(" ----------------------------- ");
for(int i=0;i<boardPositions.length;i++){
System.out.print(i + "|\t");
for(int j=0;j<boardPositions[i].length;j++){
System.out.print(" "+boardPositions[i][j] + "\t");
}
System.out.println();
}
}
private static void displayPossibleMoves(){
System.out.println("\n0 -> 1 move up // 2 moves right.\n" +
"1 -> 2 moves up // 1 move right.\n" +
"2 -> 2 moves up // 1 move left.\n" +
"3 -> 1 move up // 2 moves left.\n" +
"4 -> 1 move down // 2 moves left.\n" +
"5 -> 1 move left // 2 moves down.\n" +
"6 -> 1 move right // 2 moves down.\n" +
"7 -> 1 move down // 2 moves right.");
}
}
Hey i don't think you need to change much. You just need to add two integers that keep track of your previous position. I tried to keep the modifications of your code to a minimum:
int previousRow = 3;
int previousColumn = 4;
and update them after you set the current position to "H":
Here is a modified version of your public static main(String[] args):
public static void main(String[] args){
fillArrays();
boolean outOfBoundsV;
boolean outOfBoundsH;
boolean positionAvailability = false;
int VerticalMove,HorizontalMove;
fillBoard();
board[3][4] = "H";
boardPositions[3][4] = true;
// add the two integers that keep track of you previous position:
int previousRow = 3;
int previousColumn = 4;
displayBoard();
int pickMove;
for(int i=1;i<=64;i++){
displayBoardPositions();
displayPossibleMoves();
do {
System.out.println("\nPick one of the displayed moves to do (0-7): ");
pickMove = scanner.nextInt();
VerticalMove = moveHorse_Vertical(pickMove);
HorizontalMove = moveHorse_Horizontal(pickMove);
outOfBoundsV = checkForOutOfBounds(VerticalMove);
outOfBoundsH = checkForOutOfBounds(HorizontalMove);
if ((outOfBoundsV)||(outOfBoundsH)){
reverse(pickMove);
}
if((!outOfBoundsV)&&(!outOfBoundsH)){
positionAvailability = checkForPositionAvailability(VerticalMove,HorizontalMove);
if((!positionAvailability)){
reverse(pickMove);
}
}
} while ((outOfBoundsV)||(outOfBoundsH)||(!positionAvailability));
// set the previous position to your current step of i:
board[previousRow][previousColumn] = String.valueOf(i);
board[VerticalMove][HorizontalMove] = "H";
//update your previous position, with your current position
previousColumn = currentColumn;
previousRow = currentRow;
boardPositions[VerticalMove][HorizontalMove] = true;
displayBoard();
}
}

JTable object [][] data

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?

Infinite while loop in java, not reading in sentinel

I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.

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