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.
Related
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());
}
}
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();
}
}
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.
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.
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 = "-------";
}