2 instance variables constantly updating each other - java

I'm having a slight problem where my instance variables kinda work as class variables at least thats what i think.
public class Lab10 {
public static void main(String[] args) {
CannonSolution MaxRange = MAXRMHC(10);
MaxRange.println();
}
public static CannonSolution MAXRMHC(int iter){
double range =0;
double newrange;
CannonSolution sol = new CannonSolution(1,1);
CannonSolution NewSol = new CannonSolution(sol.SendCanang(),sol.SendCanvel());
range = Cannon.GetMaxRange(sol.SendCanang(),sol.SendCanvel());
for(int i =0;i<iter;i++){
NewSol.smallChange();
newrange = Cannon.GetMaxRange(NewSol.SendCanang(), NewSol.SendCanvel());
if(range <= newrange){
System.out.println(range+" is smaller than "+newrange);
NewSol.println();
range = newrange;
sol = NewSol;
}else if (range > newrange){
NewSol.println();
sol.println();
}else{
System.out.println("I don't work");
}
}
System.out.println();
System.out.println(range);
return (sol);
}
}
public class CannonSolution {
private double canang;
private double canvel;
public CannonSolution(double ang, double vel){
if(ang <25.0 || ang >55.0){
canang = Randomang();
}else{
canang = ang;
}
if(vel <1500.0 || vel > 1650.0){
canvel = Randomvel();
}else{
canvel = vel;
}
}
public double SendCanang(){
return (canang);
}
public double SendCanvel(){
return (canvel);
}
private static double Randomang(){
double ang = RandomNumber.RandomNum(25,55);
return ang;
}
private static double Randomvel(){
double vel = RandomNumber.RandomNum(1500,1650);
return vel;
}
private void smallChangeVel(){
double vel = canvel;
double number = (double) RandomNumber.UI(1,30);
double updown = RandomNumber.UI(1,2);
if(updown ==1 ){
vel = vel + number;
}else{
vel = vel - number;
}
if(vel <1500){
vel =1500.0;
}else if (vel > 1650){
vel = 1650.0;
}
canvel = vel;
}
private void smallChangeAng(){
double ang = canang;
double number = RandomNumber.UI(1,3);
double updown = RandomNumber.UI(1,2);
if(updown ==1 ){
ang = ang + number;
}else{
ang = ang - number;
}
if(ang <25){
ang =25.0;
}else if (ang > 55){
ang = 55.0;
}
canang= ang;
}
public void smallChange(){
double updown = RandomNumber.UI(1,2);
if(updown == 1){
smallChangeAng();
}else{
smallChangeVel();
}
}
public void print()
{
System.out.println(canang);
System.out.print(canvel);
}
public void println()
{
print();
System.out.println();
}
}
http://pastebin.com/zJWPyz7Q
http://pastebin.com/EYugr96p
The problem is that when Newsol is changed using the smallchange method it changes both newsol and sol. I've been stuck on this for a while.
Sorry, I wasn't too sure how to format this im new to asking in stackoverflow.

After the line
sol = Newsol;
you have discarded the old object referenced by sol and now both variables sol and Newsol identify the same object. This would lead to the behavior you are seeing.

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

How to use array of objects in this context?

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

How do I input&solve expressions like sin(60)*50/4 in my simple calculator(without GUI) in Java?

I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}

Missing Format Argument Exception

When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.

The hierarchy of the type 'classname' is incosistent--java error in eclipse

I have a class CircleController, which extends a class VehicleController, and I am confused as to why I am getting this error. any help would be greatly appreciated.
The CircleController is...
import java.math.*;
import javax.realtime.*;
public class CircleController extends VehicleController{
public final static int XMiddle = 50;
public final static int YMiddle = 50;
public final static int radius = 25;
//private GroundVehicle v;
public CircleController(Simulator s, GroundVehicle v){
super(s,v);
}
public CircleController(Simulator s, GroundVehicle v, SchedulingParameters sched, ReleaseParameters release){
super(s,v,sched, release);
}
public Control getControl(int sec, int msec){
double position[] = this.newVehic.getPosition();
double dist = Math.sqrt((position[0]-XMiddle)*(position[0]-XMiddle)+(position[1]-YMiddle)*(position[1]-YMiddle));
double angleFromCircleMiddle = Math.atan2(position[1]-YMiddle,position[0]-XMiddle);
double omega=0;
double speed =Simulator.maxTransSpeed;
double angleDelta = position[2]-angleFromCircleMiddle; //angle we need to turn
Control c = new Control(speed, omega);
if (dist<radius+.01){// inside the circle so need to move outwards
//double desiredTheta = angleFromCircleMiddle;
omega = angleDelta/(100.0/1000.0);
//checking omega
if (omega>Math.PI/4)
omega = Math.PI/4;
else if (omega<-Math.PI/4)
omega=-Math.PI/4;
c = new Control(speed, omega);
}
else if (dist+.01>radius){
angleDelta = -angleDelta; //coming from outside inwards
omega = angleDelta/(100.0/1000.0);
//checking omega
if (omega>Math.PI/4)
omega = Math.PI/4;
else if (omega<-Math.PI/4)
omega=-Math.PI/4;
c = new Control(speed, omega);
}
else{
//speed = radius*omega
omega = speed/radius;
c = new Control(speed, omega);
}
c=avoidWalls(this.newVehic.getPosition());
return c;
}
}
The VehicleController class is...
import javax.realtime.*;
public class VehicleController extends RealtimeThread{
protected Simulator newSim;
protected GroundVehicle newVehic;
private double prevTime;
private int numSides;
public double turnDuration;
public double edgeTravelDuration;
public boolean isTurning = false;
public boolean controllerInitialized=false;
public double timeOfManoeuverStart;
protected static int numControllers=0;
protected int controllerID = 0;
private static double avoidWallDist = 15;
private static double timeUpdateInterval = .1;
//constants
private final int diameter=50;
public VehicleController(Simulator s, GroundVehicle v){
//error if input is incorrect
if (s==null)
throw new IllegalArgumentException("error, a null Simulator was inputted.");
if (v==null)
throw new IllegalArgumentException("error, a null Ground Vehicle was inputted.");
this.newSim=s;
this.newVehic=v;
setNumSides(5);
synchronized(VehicleController.class){
controllerID=numControllers;
numControllers++;
}
}
public VehicleController(Simulator s, GroundVehicle v, SchedulingParameters schedule, ReleaseParameters release){
//error if input is incorrect
if (s==null)
throw new IllegalArgumentException("error, a null Simulator was inputted.");
if (v==null)
throw new IllegalArgumentException("error, a null Ground Vehicle was inputted.");
this.newSim=s;
this.newVehic=v;
setNumSides(5);
synchronized(VehicleController.class){
controllerID=numControllers;
numControllers++;
}
}
private void initializeController(){
/* The bulk of this method is to determine how long to spend turning at
* each corner of the polygon, and how long to spend driving along each
* edge. We calculate turnDuration and edgeTravelDuration, and then use
* these inside getControl to decide when to switch from turning to
* travelling straight and back again. */
double interiorAngle = (Math.PI/180)*(180+180*(numSides-3))/numSides;
double turningAngle = Math.PI - interiorAngle;
double minTurningRadius = newSim.minTransSpeed/newSim.maxRotSpeed; // v/w=r
double arcLength = (turningAngle)*minTurningRadius; //need to know at what point we need to start turning
turnDuration = arcLength/newSim.minTransSpeed; //shortest length needed to make this turn
double edgeLength = diameter*Math.cos(interiorAngle/2) -(2*minTurningRadius*Math.tan((turningAngle)/2));
edgeTravelDuration =edgeLength/newSim.maxTransSpeed;
isTurning=true; //meaning we are done with the straightaway and need to turn.
timeOfManoeuverStart = -turnDuration/2.0;
controllerInitialized=true;
}
public Control getControl(int sec, int msec) {
double controlTime = sec+msec*1E-3;
Control c = null;
if (isTurning) {
if (controlTime - timeOfManoeuverStart < turnDuration)
c = new Control(newSim.minTransSpeed, newSim.maxRotSpeed);
else {
isTurning = false;
timeOfManoeuverStart = controlTime;
c = new Control(newSim.maxTransSpeed, 0);
}
}
else {
if (controlTime - timeOfManoeuverStart < edgeTravelDuration)
c = new Control(newSim.maxTransSpeed, 0);
else {
isTurning = true;
timeOfManoeuverStart = controlTime;
c = new Control(newSim.minTransSpeed, newSim.maxRotSpeed);
}
}
return c;
}
public void setNumSides(int n){
if (n>10 || n<3)
numSides=numSides;
else
numSides=n;
initializeController();
}
public int getNumSides(){
return numSides;
}
public void run(){
int sec=0, mSec=0;
double currentTime=0;
//prevTime=0;
// The simulation time is called by multiple threads, so we must put it in a simulator block.
double prevTime=0;
while (currentTime<100){
synchronized(newSim){
sec = newSim.getCurrentSec();
mSec = newSim.getCurrentMSec();
currentTime =sec+mSec/1000.0;
if (currentTime>prevTime+ timeUpdateInterval){
prevTime = currentTime;
Control c =getControl(sec,mSec);
if (c!=null){
newVehic.controlVehicle(c);
}
}
newSim.notifyAll();
}
}
}
protected Control avoidWalls(double[] pos) {
if (pos[0] > 100 - avoidWallDist && pos[1] > 100 - avoidWallDist) {
if (pos[2] > -3 * Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] > 100 - avoidWallDist && pos[1] < 0 + avoidWallDist) {
if (pos[2] > 3 * Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] < 0 + avoidWallDist && pos[1] > 100 - avoidWallDist) {
if (pos[2] > -Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] < 0 + avoidWallDist && pos[1] < 0 + avoidWallDist) {
if (pos[2] > Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] > 100 - avoidWallDist) {
if (pos[2] > 0) {
return new Control(5, Math.PI/4);
} else {
return new Control(5, -Math.PI/4);
}
}
if (pos[0] < 0 + avoidWallDist) {
if (pos[2] > 0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[1] < 0 + avoidWallDist) {
if (pos[2] > Math.PI / 2) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[1] > 100- avoidWallDist) {
if (pos[2] > -Math.PI / 2) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
return null;
}
}

Categories