I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.
Related
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();
}
}
so im super stuck.. im doing my toString() method and it needs to show a bar graph with stars that correlate with the number of grades. ex.
how it should look if 5 As, 3 Bs, 3 Cs, 2 Ds, 1 F,
*****A
***B
***C
**D
*F
my teacher gave me a start, but i have no idea what to do besides concatenating the single variable thats been given. keep in mind I'm learning still and haven't learned the other ways such as string building or arrays
public class GradeDistribution {
private int mNumberAs;
private int mNumberBs;
private int mNumberCs;
private int mNumberDs;
private int mNumberFs;
public GradeDistribution(int numberOfAs, int numberOfBs,
int numberOfCs, int numberOfDs,
int numberOfFs)
{
mNumberAs = numberOfAs;
mNumberBs = numberOfBs;
mNumberCs = numberOfCs;
mNumberDs = numberOfDs;
mNumberFs = numberOfFs;
}
public GradeDistribution()
{
mNumberAs = 0;
mNumberBs = 0;
mNumberCs = 0;
mNumberDs = 0;
mNumberFs = 0;
}
public void setAllGrades(int A,int B, int C, int D, int F)
{
mNumberAs = A;
mNumberBs = B;
mNumberCs = C;
mNumberDs = D;
mNumberFs = F;
}
public void setNumberAs( int A)
{
mNumberAs = A;
}
public void setNumberBs(int B)
{
mNumberBs = B;
}
public void setNumberCs(int C)
{
mNumberCs = C;
}
public void setNumberDs(int D)
{
mNumberDs = D;
}
public void setNumberFs(int F)
{
mNumberFs = F;
}
public int getNumberOfGrades()
{
return mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
}
public int getPercentAs()
{ double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageAs = (mNumberAs / totalGrade * 100);
return (int)averageAs;
}
public int getPercentBs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageBs = (mNumberBs / totalGrade * 100);
return (int)averageBs;
}
public int getPercentCs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageCs = (mNumberCs / totalGrade * 100);
return (int) averageCs;
}
public int getPercentDs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageDs = (mNumberDs / totalGrade * 100);
return (int) averageDs;
}
public int getPercentFs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageFs = (mNumberFs / totalGrade * 100);
return (int)averageFs;
}
public String toString()
{
String output = "";
for(int a = 1; a <= mNumberAs; a++)
{
}
}
}
In your for loop you are iterating over the number of As that were given. So you can append * to your string as you iterate. output = output + "*"; When the loop is done, append an A and a new line \n, and then do the same for Bs, Cs, etc:
String output = "";
for(int a = 1; a <= mNumberAs; a++) {
output = output + "*";
}
output = output + "A\n";
// do the same for the number of Bs, Cs, etc
I have an array list of type car.
I have an overriding toString method which prints my car in the desired format.
I'm using the arraylist.get(index) method to print the cars.
I only have one for now it works, but I want it do print for all of the cars in the array list.
This is my code:
public class Garage {
private static int carsCapacity = 30;
ArrayList<Cars> myGarage;
public Garage() {
Scanner scanAmountOfCars = new Scanner(System.in);
System.out.println("Please limit the number of car the garage can contain.");
System.out.println("If greater than 50, limit will be 30.");
int validAmount = scanAmountOfCars.nextInt();
if (validAmount <= 50) {
carsCapacity = validAmount;
myGarage = new ArrayList<Cars>();
}
System.out.println(carsCapacity);
}
public void addCar() {
Cars car = new Cars(Cars.getID(), Cars.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car);
//System.out.println(car);
}
public static int getCarsCapacity() {
return carsCapacity;
}
#Override
public String toString() {
return "Garage [Car:" + myGarage.get(0).getPlateNum() + " ID:" + myGarage.get(0).getCarID() + " Position:" + Cars.getPosition() +
" Assigned to:" + Cars.getAssignedTo().getId() + "(" + Cars.getAssignedTo().getName()
+ ")" + " Parked at:" + Cars.convert(myGarage.get(0).getCurrTime()) + "]";
}
}
I also put the Cars class in case you need it:
public class Cars {
private String carID;
private String plateNum;
private static String position;
private static Attendant assignedTo;
private long currTime;
static String[] tempArray2 = new String[Garage.getCarsCapacity()];
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
Cars.position = position;
Cars.assignedTo = assignedTo;
this.currTime = currTime;
}
private static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
tempArray2[x] = ("CR" + (x + 1));
}
}
public static String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < tempArray2.length; x++) {
if (tempArray2[x] != null) {
tempID = tempArray2[x];
tempPos = tempArray2[x];
getPos(tempPos);
tempArray2[x] = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public static Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public static String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
}
Your Garage should have the implementation of toString() which uses ArrayList#toString() implementation:
public String toString() {
return "Garage: " + myGarage.toString();
}
Also remember to implement toString() in Cars.java.
public String toString() {
return "[" + this.carID + " " +
this.plateNum + " " +
Cars.position + " " +
Cars.assignedTo.toString + " " +
String.valueOf(this.currTime) + "]"
}
I am creating a program that automates creation of player characters. Below is my PlayerCharacter class. I have noticed that I repeat many operations on different variables.
public class PlayerCharacter {
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
public void generateAbilityScoresMethod1() {
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for(int i = 0; i < 3; i++) {
strRolls[i] = dice.Dice.D6.getNewRoll();
strength += strRolls[i];
dexRolls[i] = dice.Dice.D6.getNewRoll();
dexterity += dexRolls[i];
conRolls[i] = dice.Dice.D6.getNewRoll();
constitution += conRolls[i];
intRolls[i] = dice.Dice.D6.getNewRoll();
intelligence += intRolls[i];
wisRolls[i] = dice.Dice.D6.getNewRoll();
wisdom += wisRolls[i];
charRolls[i] = dice.Dice.D6.getNewRoll();
charisma += charRolls[i];
}
}
public int getStrength() {
return strength;
}
public void printStrRolls() {
System.out.println("Str: roll 1 = " + strRolls[0]);
System.out.println("Str: roll 2 = " + strRolls[1]);
System.out.println("Str: roll 3 = " + strRolls[2]);
}
public int getDexterity() {
return dexterity;
}
public void printDexRolls() {
System.out.println("Dex: roll 1 = " + dexRolls[0]);
System.out.println("Dex: roll 2 = " + dexRolls[1]);
System.out.println("Dex: roll 3 = " + dexRolls[2]);
}
public int getConsitution() {
return constitution;
}
public void printConRolls() {
System.out.println("Con: roll 1 = " + conRolls[0]);
System.out.println("Con: roll 2 = " + conRolls[1]);
System.out.println("Con: roll 3 = " + conRolls[2]);
}
public int getIntelligence() {
return intelligence;
}
public void printIntRolls() {
System.out.println("Int: roll 1 = " + intRolls[0]);
System.out.println("Int: roll 2 = " + intRolls[1]);
System.out.println("Int: roll 3 = " + intRolls[2]);
}
public int getWisdom() {
return wisdom;
}
public void printWisRolls() {
System.out.println("Wis: roll 1 = " + wisRolls[0]);
System.out.println("Wis: roll 2 = " + wisRolls[1]);
System.out.println("Wis: roll 3 = " + wisRolls[2]);
}
public int getCharisma() {
return charisma;
}
public void printCharRolls() {
System.out.println("Char: roll 1 = " + charRolls[0]);
System.out.println("Char: roll 2 = " + charRolls[1]);
System.out.println("Char: roll 3 = " + charRolls[2]);
}
public void printAbilities() {
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}
How can I accomplish the same tasks in a more efficient way?
You may declare a class Ability and make strength, dexterity, ... instances thereof. The following snippet might be a start:
class Ability {
private final int[] rolls;
private int value;
public Ability(int dice) {
rolls = new int[dice];
}
public int roll() {
value = 0;
for (int i = 0; i < rolls.length; i++) {
rolls[i] = dice.Dice.D6.getNewRoll();
value += rolls[i];
}
return value;
}
public int getValue() {
return value;
}
public void printRolls() {
// ... tbd ...
}
}
You can the use the abilities like ...
Ability strength;
strength = new Ability(3);
strength.roll(); // get new value
System.out.println(strength.getValue()); // e.g. print
strength.printRolls(); // e.g. print rolls
How about this:
public void printRolls( String label, int[] rolls) {
System.out.println(label + ": roll 1 = " + rolls[0]);
System.out.println(label + ": roll 2 = " + rolls[1]);
System.out.println(label + ": roll 3 = " + rolls[2]);
}
You can cut down repeated code line this
enum Attribute {
Str, Con, Dex, Int, Wis, Cha
}
class PlayerCharacter {
static final Random rand = new Random();
static final Attribute[] ATTRS = Attributes.values();
final int[] attr = new int[ATTRS.length];
PlayerCharacter() {
for(int i = 0; i < attr.length; i++)
attr[i] = rand.nextInt(6) + rand.nextInt(6) + rand.nextInt(6) + 3;
}
public int getAttr(Attribute attr) {
return attrs[attr.ordinal()];
}
public void printAbilities() {
for(int i = 0; i < ATTRS.length; i++)
System.out.println(ATTRS[i]+ " = " + attrs[i]);
}
Note: you may want any other attributes like HP, AC, Max HP, Level, XP, etc.
The only thing I would do there is to create a static dice rolling method which returns the array you need, so you can generate dice roll arrays for any type of dice:
public static int[] roll(int numberOfDice, int sidesOnEachDie) {
int[] result = new int[numberOfDice];
for(int i = 0; i < numberOfDice; ++i) {
result[i] = 1 + (int) Math.floor(Math.random() *
(double) sidesOnEachDie);
}
return result;
}
Then you can call, for example:
intRolls = roll(3, 6);
which will give the result of rolling 3D6 in an int array.
You could keep all your properties in an int[]. So rather than having strength, dexterity, constitution, intelligence, wisdom, charisma as separate variables have one
int[] characteristics;
then 0 would be strength; 1 would be dexterity and so on.
To keep the roll values you would need a int[][].
This is less code; it is not "more efficient" in CPU use or memory use, but makes the code shorter to write and read. I assume dice rolls are random regardless of their order.
package example;
public class PlayerCharacter
{
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
private int getScore(Dice d, int[] storage)
{
for (int i=0; i<storage.length; i++)
{
storage[i] = d.getNewRoll();
}
int result = 0;
for (int i=0; i<storage.length; i++) { result += storage[i]; }
}
public void generateAbilityScoresMethod1()
{
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for (int i = 0; i < 3; i++)
{
strength = getScore(dice.Dice.D6, strRolls);
dexterity = getScore(dice.Dice.D6, dexRolls);
constitution = getScore(dice.Dice.D6, conRolls);
intelligence = getScore(dice.Dice.D6, intRolls);
wisdom = getScore(dice.Dice.D6, wisRolls);
charisma = getScore(dice.Dice.D6, charRolls);
}
}
public int getStrength()
{
return strength;
}
private void printArrayRolls(String label, int[] rolls)
{
for (int i=0; i < rolls.length; i++)
{
System.out.println(label + ": roll " + rolls[i]);
}
}
public void printStrRolls()
{
printArrayRolls("Str", strRolls);
}
public int getDexterity()
{
return dexterity;
}
public void printDexRolls()
{
printArrayRolls("Dex", dexRolls);
}
public int getConsitution()
{
return constitution;
}
public void printConRolls()
{
printArrayRolls("Con", conRolls);
}
public int getIntelligence()
{
return intelligence;
}
public void printIntRolls()
{
printArrayRolls("Int", intRolls);
}
public int getWisdom()
{
return wisdom;
}
public void printWisRolls()
{
printArrayRolls("Wis", wisRolls);
}
public int getCharisma()
{
return charisma;
}
public void printCharRolls()
{
printArrayRolls("Char", charRolls);
}
public void printAbilities()
{
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}
This is less code; it is not "efficient" in CPU use or memory use, but makes the code shorter to write and read. I assume dice rolls are random regardless of their order.
package example;
public class PlayerCharacter
{
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
private int getScore(Dice d, int[] storage)
{
for (int i=0; i<storage.length; i++)
{
storage[i] = d.getNewRoll();
}
int result = 0;
for (int i=0; i<storage.length; i++) { result += storage[i]; }
}
public void generateAbilityScoresMethod1()
{
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for (int i = 0; i < 3; i++)
{
strength = getScore(dice.Dice.D6, strRolls);
dexterity = getScore(dice.Dice.D6, dexRolls);
constitution = getScore(dice.Dice.D6, conRolls);
intelligence = getScore(dice.Dice.D6, intRolls);
wisdom = getScore(dice.Dice.D6, wisRolls);
charisma = getScore(dice.Dice.D6, charRolls);
}
}
public int getStrength()
{
return strength;
}
private void printArrayRolls(String label, int[] rolls)
{
for (int i=0; i < rolls.length; i++)
{
System.out.println(label + ": roll " + rolls[i]);
}
}
public void printStrRolls()
{
printArrayRolls("Str", strRolls);
}
public int getDexterity()
{
return dexterity;
}
public void printDexRolls()
{
printArrayRolls("Dex", dexRolls);
}
public int getConsitution()
{
return constitution;
}
public void printConRolls()
{
printArrayRolls("Con", conRolls);
}
public int getIntelligence()
{
return intelligence;
}
public void printIntRolls()
{
printArrayRolls("Int", intRolls);
}
public int getWisdom()
{
return wisdom;
}
public void printWisRolls()
{
printArrayRolls("Wis", wisRolls);
}
public int getCharisma()
{
return charisma;
}
public void printCharRolls()
{
printArrayRolls("Char", charRolls);
}
public void printAbilities()
{
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}
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.