Why won't this PrintWriter populate this file? - java

I have a program which takes Giraffes from a text file, creates an ArrayList and LinkedList out of them (redundant, I know... LinkedList was a requirement of the second part of the assignment and I liked my ArrayList), sorts out who their parents are, and then is supposed to print a VBA macro out to a file.
The file (D:\\Java\\Macro.txt) is created, but it isn't populated with anything. Why isn't anything getting printed to the file? I think that there is an issue creating an array to return to the main function though.
I suspect that the problem is within the GetYearGroup method in the Herd Class, and the way that it is interfacing with the PrintWriter located on lines 51-83 of the Main class.
Here is the code:
HW4_Name.java (main)
package giraffe;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class HW4_Name {
public static void main(String[] args) throws IOException {
ArrayList<Giraffe> giraffes = new ArrayList<>();
String temp[] = new String[13];
String header = "";
String fileLocation = "theHerd.txt";
File textFile = new File(fileLocation);
Scanner in = new Scanner(textFile);
if (textFile.canRead()) {
header = in.nextLine();
while (in.hasNextLine()) {
temp = in.nextLine().split("\\t", 13);
giraffes.add(new Giraffe(temp));
}
}
Herd herd = new Herd();
for(int i = 0; i < giraffes.size(); i++){
Giraffe g = giraffes.get(i);
herd.Add(g);
}
int nGiraffes = herd.Size();
for(int i = 0; i < nGiraffes; i++){
Giraffe g = herd.GetAt(i);
int nSire = g.getSireId();
if (nSire != -1){
g.setSire(herd.Find(nSire));
}
int nDam = g.getDamId();
if (nDam != -1){
g.setDam(herd.Find(nDam));
}
}
in.close();
PrintWriter pw = new PrintWriter("C:\\Java\\Macro.txt");
int nHeight = 500;
int nWidth = 900;
int nYearHeight = nHeight / 13;
int nRectangle = 0;
for(int i = 0; i < 13; i++){
int nLowYear = 50 + 5 * i;
Giraffe[] ThisGroup = herd.GetYearGroup(nLowYear, nLowYear + 5);
int nThisGroup = ThisGroup.length;
int nXSpacing = nWidth / (nThisGroup + 1);
int nYPos = 10 + nYearHeight * i;
for(int j = 0; j < nThisGroup; j++){
nRectangle++;
int nXPos = 10 + nXSpacing/2 + nXSpacing * j;
Giraffe g = ThisGroup[j];
g.setRectangle(nRectangle);
String strName = g.getName();
pw.println("Call Box(" + nXPos + ", " + nYPos + ", \"" +strName + "\")");
}
}
for(int i = 0; i < nGiraffes; i++){
Giraffe g = herd.GetAt(i);
Giraffe gSire = g.getSire();
if (gSire != null){
int nParentRectangle = gSire.getRectangle();
nRectangle = g.getRectangle();
if (nParentRectangle > 0 && nRectangle > 0){
pw.println("Call DadLine(" + nParentRectangle + ", " + nRectangle + ")");
}
}
Giraffe gDam = g.getDam();
if(gDam != null){
int nParentRectangle = gDam.getRectangle();
if (nParentRectangle > 0 && nRectangle > 0){
pw.println("Call MomLine(" + nParentRectangle + ", " + nRectangle + ")");
}
}
}
pw.close();
}
}
Giraffe.java
package giraffe;
import java.util.ArrayList;
public class Giraffe extends Object {
private String birthLocation, subSpecies, zoo, city, state, event, name,
localId, sex, eachGiraffe;
private int gId, birthYear, sireId, damId, gRectangle;
private Giraffe gSire, gDam;
public Giraffe(String array[]){
this.sex = String.format("%-1s",array[1]);
this.birthLocation = String.format("%-12s",array[5]);
this.localId = String.format("%-7s",array[6]);
this.name = String.format("%-20s",array[7]);
this.subSpecies = String.format("%-14s",array[8]);
this.zoo = String.format("%-35s",array[9]);
this.city = String.format("%-17s",array[10]);
this.state = String.format("%-13s",array[11]);
this.event = String.format("%-7s",array[12]);
this.gId = Integer.parseInt(array[0]);
this.birthYear = Integer.parseInt(array[2].substring(0,4));
if(array[3].equals("WILD") || array[3].equals("UNK")){
this.sireId = -1;
}
else{
this.sireId = Integer.parseInt(array[3]);
}
if(array[4].equals("WILD") || array[4].equals("UNK")){
this.damId = -1;
}
else{
this.damId = Integer.parseInt(array[4]);
}
}
public String getName(){
return this.name;
}
public int getId(){
return gId;
}
public int getBirthYear(){
return birthYear;
}
public int getSireId(){
return sireId;
}
public int getDamId(){
return damId;
}
public Giraffe getSire(){
return gSire;
}
public int getRectangle(){
return gRectangle;
}
public Giraffe getDam(){
return gDam;
}
public void setSire(Giraffe nSire){
this.gSire = nSire;
}
public void setDam(Giraffe nDam){
this.gDam = nDam;
}
public void setRectangle(int nRectangle){
this.gRectangle = nRectangle;
}
public String toString(){
eachGiraffe = ("" + this.gId);
return eachGiraffe;
}
}
Herd.java
package giraffe;
public class Herd extends LinkedList{
public Herd(){
}
public void Add(Giraffe g){
InsertRight(g);
}
public Giraffe Find(int idNumber){
Giraffe g = null;
Node currNode = start;
while(currNode != null && currNode.o.getId() != idNumber){
currNode = currNode.next;
}
if(currNode.o.getId() == idNumber){
g = currNode.o;
}
return g;
}
public Giraffe GetAt(int nIndex){
Giraffe g = null;
Node currNode = start;
for(int i = 0; i < nIndex; i++){
if(currNode != null){
currNode = currNode.next;
}
}
g = currNode.o;
return g;
}
public Giraffe[] GetYearGroup(int nBegin, int nEnd){
int nGiraffes = Size();
int nInGroup = 0;
for(int i = 0; i < nGiraffes; i++){
Giraffe g = GetAt(i);
int nBirthYear = g.getBirthYear();
if (nBegin <= nBirthYear && nBirthYear < nEnd){
nInGroup++;
}
}
Giraffe[] gary = new Giraffe[nInGroup];
nInGroup = 0;
for(int i = 0; i < nGiraffes; i ++){
Giraffe g = GetAt(i);
int nBirthYear = g.getBirthYear();
if(nBegin <= nBirthYear && nBirthYear < nEnd){
gary[nInGroup] = g;
nInGroup++;
}
}
return gary;
}
}
LinkedList.java
package giraffe;
public class LinkedList {
protected Node start;
private int errorReturn;
public LinkedList(){
start = null;
}
public LinkedList(int errorValue){
start = null;
errorReturn = errorValue;
System.out.println(errorReturn);
}
public boolean isEmpty(){
return (start == null);
}
public void InsertRight(Giraffe data){
Node currNode;
if (start == null){
start = new Node(data,start);
}
else{
currNode = start;
while (currNode.next != null){
currNode = currNode.next;
}
currNode.next = new Node (data, null);
}
}
public int Size(){
int length = 0;
Node currNode = start;
while(currNode != null){
length++;
currNode = currNode.next;
}
return length;
}
public void Display(){
Node currNode = start;
System.out.println("List contents: ");
while (currNode != null){
currNode = currNode.next;
}
System.out.println("--------------------------");
}
}
Node.java
package giraffe;
public class Node {
Giraffe o;
Node next;
public Node(Giraffe giraffe, Node nextNode){
o = giraffe;
next = nextNode;
}
}
Solution
Thank you to durron597 for pointing out that the birthYear function was not comparable to the GetYearGroup function.
Replacing:
for(int i = 0; i < 13; i++){
int nLowYear = 50 + 5 * i;
With:
for(int i = 0; i < 13; i++){
int nLowYear = 1950 + 5 * i;
Resolved the issue.

I see two problems, both of which could result in the things you're seeing:
You are outputting to the C:\\Java\\Macro.txt directory, but you are using a relative path to find your theHerd.txt. Try changing your theHerd.txt file to an absolute path, or use Class.getResourceAsStream() if the file is on your classpath.
Use a debugger to see if the Giraffe objects are getting created at all
Your birth year check seems really weird:
for(int i = 0; i < 13; i++){
int nLowYear = 50 + 5 * i;
Giraffe[] ThisGroup = herd.GetYearGroup(nLowYear, nLowYear + 5);
This is only going to check years in the range 50, 55, up to 115. However, in your Giraffe class, you do this:
this.birthYear = Integer.parseInt(array[2].substring(0,4));
This is only going to work (i.e. not throw an ArrayIndexOutOfBounds exception) for 4 digit date years, none of which are in the range 50-115. However, if you set your year to a value like 0073 (you must put the leading zeroes) then your program will print results like Call Box(235, 162, "GiraffeName "). You probably want to change that 50 to 1950.
Your program has other code smells; I suggest reading things like (in order of increasing time commitment):
Java Encapsulation Concept not clear
Java naming conventions
Single Responsibility Principle
Clean Code, by Robert Martin
But these two bits of code should get you started.

Related

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

Android - An algorithm to check recursively if a map is solvable

I am making an android Hashikawekero puzzle game, I have implemented a algorithm to spawn nodes (Islands) at random positions using a 2-d array this works fine it creates the node at random position but most of the times the map cant be solved. The map nodes spawn at random.
BoardCreation.java Class - this generates the map.
package Island_and_Bridges.Hashi;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import java.util.Random;
import static junit.framework.Assert.*;
//This class Creates the map by random using a 2d array
public class BoardCreation {
// This class member is used for random initialization purposes.
static private final Random random = new Random();
// The difficulty levels.
private static final int EASY = 0;
static public final int MEDIUM = 1;
static public final int HARD = 2;
static public final int EMPTY = 0;
private static int ConnectionFingerprint(BoardElement start, BoardElement end) {
int x = start.row * 100 + start.col;
int y = end.row * 100 + end.col;
// Swap to get always the same fingerprint independent whether we are called
// start-end or end-start
if (x > y ) {
int temp = x;
x = y;
y = temp;
}
Log.d("", String.format("%d %d" , x ,y));
return x ^ y;
}
public class State {
// The elements of the board are stored in this array.
// A value defined by "EMPTY" means that its not set yet.
public BoardElement [][] board_elements = null;
public int [][] cell_occupied = null;
// The width of the board. We only assume squared boards.
public int board_width=0;
public State(int width) {
board_width = width;
board_elements = new BoardElement[width][width];
cell_occupied = new int[width][width];
}
public State CloneWithoutConnections() {
State newstate = new State(board_width);
if (board_elements != null) {
newstate.board_elements = new BoardElement[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
for (int j = 0; j < board_elements.length; ++j) {
if (board_elements[i][j] == null)
continue;
newstate.board_elements[i][j] = board_elements[i][j].clone();
}
}
}
if (cell_occupied != null) {
assert board_elements != null;
newstate.cell_occupied = new int[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
System.arraycopy(cell_occupied[i], 0, newstate.cell_occupied[i], 0, board_elements.length);
}
}
return newstate;
}
public void AddToBridgeCache(BoardElement first, BoardElement second) {
if (first == null || second == null) { return; }
final int fingerprint = ConnectionFingerprint(first, second);
Log.d(getClass().getName(),
String.format("Fingerprint of this bridge %d", fingerprint));
// mark the end points as occupied.
cell_occupied[first.row][first.col] = fingerprint;
cell_occupied[second.row][second.col] = fingerprint;
int dcol = second.col - first.col;
int drow = second.row - first.row;
if (first.row == second.row) {
for (int i = (int) (first.col + Math.signum(dcol)); i != second.col; i += Math.signum(dcol)) {
cell_occupied[first.row][i] = fingerprint;
String.format("deleting bridge");
}
} else {
assert first.col == second.col;
for (int i = (int) (first.row + Math.signum(drow)); i != second.row; i+= Math.signum(drow)) {
cell_occupied[i][first.col] = fingerprint;
}
}
}
} // end of state
private State current_state, old_state;
static private final int WIDTH_EASY = 7;
private void NewGame(int hardness) {
switch(hardness) {
case EASY:
Log.d(getClass().getName(), "Initializing new easy game");
InitializeEasy();
old_state = getCurrentState().CloneWithoutConnections();
break;
}
}
public void ResetGame() {
if (old_state != null) {
Log.d(getClass().getName(), "Setting board_elements to old_elements");
setCurrentState(old_state.CloneWithoutConnections());
} else {
Log.d(getClass().getName(), "old_lements are zero");
}
}
public BoardCreation(int hardness) {
NewGame(hardness);
}
public boolean TryAddNewBridge(BoardElement start, BoardElement end, int count) {
assertEquals(count, 1);
assert (start != null);
assert (end != null);
final int fingerprint = ConnectionFingerprint(start, end);
Log.d(getClass().getName(),
String.format("considering (%d,%d) and (%d,%d)", start.row,start.col, end.row,end.col));
if (start.row == end.row && start.col == end.col) {
Log.d(getClass().getName(), "Same nodes selected!");
return false;
}
assert count > 0;
int dcol = end.col - start.col;
int drow = end.row - start.row;
// It must be a vertical or horizontal bridge:
if (Math.abs(dcol) > 0 && Math.abs(drow) > 0) {
Log.d(getClass().getName(), "not a horizontal or vertical bridge.");
return false;
}
// First we check whether start and end elements can take the specified bridge counts.
int count_start = start.GetCurrentCount();
int count_end = end.GetCurrentCount();
if (count_start + count > start.max_connecting_bridges ||
count_end + count > end.max_connecting_bridges) {
Log.d(getClass().getName(), "This Bridge is not allowed");
return false;
}
Log.d(getClass().getName(),
String.format("Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row, start.col,
count_end, end.row, end.col));
Connection start_connection = null;
Connection end_connection = null;
// Next we check whether we are crossing any lines.
if (start.row == end.row) {
for (int i = (int) (start.col + Math.signum(dcol)); i != end.col; i += Math.signum(dcol)) {
if (getCurrentState().cell_occupied[start.row][i] > 0 &&
getCurrentState().cell_occupied[start.row][i] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
assert start.col != end.col;
if (start.col > end.col) {
start.connecting_east = GetOrCreateConnection(end, start.connecting_east);
end.connecting_west = GetOrCreateConnection(start, end.connecting_west);
start_connection = start.connecting_east;
end_connection = end.connecting_west;
} else {
start.connecting_west = GetOrCreateConnection(end, start.connecting_west);
end.connecting_east = GetOrCreateConnection(start, end.connecting_east);
start_connection = start.connecting_west;
end_connection = end.connecting_east;
}
} else {
assert start.col == end.col;
for (int i = (int) (start.row + Math.signum(drow)); i != end.row ; i += Math.signum(drow)) {
if (getCurrentState().cell_occupied[i][start.col] > 0 &&
getCurrentState().cell_occupied[i][start.col] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
if (start.row > end.row ) {
start.connecting_north = GetOrCreateConnection(end, start.connecting_north);
end.connecting_south = GetOrCreateConnection(start, end.connecting_south);
start_connection = start.connecting_north;
end_connection = end.connecting_south;
} else {
start.connecting_south= GetOrCreateConnection(end, start.connecting_south);
end.connecting_north = GetOrCreateConnection(start, end.connecting_north);
start_connection = start.connecting_south;
end_connection = end.connecting_north;
}
}
start_connection.destination = end;
end_connection.destination = start;
start_connection.second += count;
end_connection.second += count;
getCurrentState().AddToBridgeCache(start, end);
Log.d(getClass().getName(),
String.format("New bridge added. Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row,start.col,
count_end, end.row,end.col));
return true;
}
private Connection GetOrCreateConnection(
BoardElement end,
Connection connection) {
if (connection!= null) { return connection; }
return new Connection();
}
#TargetApi(Build.VERSION_CODES.N)
private void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
setCurrentState(new State(WIDTH_EASY));
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
System.out.println();
}
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
}
private void setCurrentState(State new_state) {
this.current_state = new_state;
}
public State getCurrentState() {
return current_state;
}
}
What algorithm could I use to make sure the Map can be Solved (Islands Connected with Bridges) before spawning the nodes.
This is what the map looks like (don't mind the design)
One thing to consider would be to start with a blank board. Place an island. Then place another island that can be connected to the first one (i.e. on one of the four cardinal directions). Connect the two with a bridge, and increment each island's count.
Now, pick one of the two islands and place another island that it can connect. Add the bridge and increment.
Continue in this way until you've placed the number of islands that you want to place.
The beauty here is that you start with an empty board, and during construction the board is always valid.
You'll have to ensure that you're not crossing bridges when you place new islands, but that's pretty easy to do, since you know where the existing bridges are.

CombSort implementation in java

I am using Comb Sort to sort out a given array of Strings. The code is :-
public static int combSort(String[] input_array) {
int gap = input_array.length;
double shrink = 1.3;
int numbOfComparisons = 0;
boolean swapped=true;
//while(!swapped && gap>1){
System.out.println();
while(!(swapped && gap==1)){
gap = (int)(gap/shrink);
if(gap<1){
gap=1;
}
int i = 0;
swapped = false;
String temp = "";
while((i+gap) < input_array.length){
numbOfComparisons++;
if(Compare(input_array[i], input_array[i+gap]) == 1){
temp = input_array[i];
input_array[i] = input_array[i+gap];
input_array[i+gap] = temp;
swapped = true;
System.out.println("gap: " + gap + " i: " + i);
ArrayUtilities.printArray(input_array);
}
i++;
}
}
ArrayUtilities.printArray(input_array);
return numbOfComparisons;
}
The problem is that while it sorts many arrays , it gets stuck in an infinite loop for some arrays, particularly small arrays. Compare(input_array[i], input_array[i+gap]) is a small method that returns 1 if s1>s2, returns -1 if s1
try this version. The string array is changed to integer array (I guess you can change it back to string version). The constant 1.3 is replaced with 1.247330950103979.
public class CombSort
{
private static final int PROBLEM_SIZE = 5;
static int[] in = new int[PROBLEM_SIZE];
public static void printArr()
{
for(int i=0;i<in.length;i++)
{
System.out.print(in[i] + "\t");
}
System.out.println();
}
public static void combSort()
{
int swap, i, gap=PROBLEM_SIZE;
boolean swapped = false;
printArr();
while ((gap > 1) || swapped)
{
if (gap > 1)
{
gap = (int)( gap / 1.247330950103979);
}
swapped = false;
for (i = 0; gap + i < PROBLEM_SIZE; ++i)
{
if (in[i] - in[i + gap] > 0)
{
swap = in[i];
in[i] = in[i + gap];
in[i + gap] = swap;
swapped = true;
}
}
}
printArr();
}
public static void main(String[] args)
{
for(int i=0;i<in.length;i++)
{
in[i] = (int) (Math.random()*PROBLEM_SIZE);
}
combSort();
}
}
Please find below implementation for comb sort in java.
public static void combSort(int[] elements) {
float shrinkFactor = 1.3f;
int postion = (int) (elements.length/shrinkFactor);
do {
int cursor = postion;
for(int i=0;cursor<elements.length;i++,cursor++) {
if(elements[i]>elements[cursor]) {
int temp = elements[cursor];
elements[cursor] = elements[i];
elements[i] = temp;
}
}
postion = (int) (postion/shrinkFactor);
}while(postion>=1);
}
Please review and let me know your's feedback.

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