I would like to set a limit to a double variable - java

This part of the program is for calculating how long it takes to face a part.
It starts with some basic info, work piece diameter, feed rate and surface speed you want to tool to operate at. Then it runs a while loop, each time the tool advances 0.010", it calculates the new rpm the piece will rotate at and calculates the time for that cut adding it all up at the end.
The problem: I need to be able to limit the rpms. As the tool gets closer to the center of the work piece the rpms will climb to a very high unattainable rpm, I want to be able to set a limit, 2000 for example.
I cannot figure out how to do that with out affecting my loop... I have searched, but I'm such a noob maybe I've stumbled across a solution that would work and never realized it, or I am not searching for the correct key words. Here is my code:
public static void main(String[] args) {
double startRadius = 6; //Radius of stock diameter
double faceFinish = 0;
double feed = .010; //Amount the tool will advance per revolution
double sfm = 200; //Surface speed of tool (Surface feet per minute)
double rpm = 0;
double totalTime = 0;
while(faceFinish < startRadius) {
startRadius -= feed; //reduces diameter by feed
rpm = (sfm * 3.82) / (startRadius * 2); //establishes new rpm per tool advance
totalTime += (feed / (feed * rpm)) * 60;
}
int hours = (int) (totalTime / 3600);
int minutes = (int) ((totalTime % 3600) / 60);
int seconds = (int) (totalTime % 60);
System.out.printf("%02d:%02d:%02d\n", hours, minutes, seconds);
}
Edit - If/else which seems to be working.
public static void main(String[] args) {
double startRadius = 6;
double faceFinish = 0;
double feed = .010;
double sfm = 200;
double rpm = 0;
double rpm2 = 0;
double total = 0;
double total2 = 0;
double totalTime = 0;
while(faceFinish < startRadius) {
startRadius -= feed;
rpm = (sfm * 3.82) / (startRadius * 2);
if(rpm > 2000) {
rpm = 2000;
total += (feed / (feed * rpm)) * 60;
}else {
total2 += (feed / (feed * rpm)) * 60;
}
totalTime = total + total2;
}
int hours = (int) (totalTime / 3600);
int minutes = (int) ((totalTime % 3600) / 60);
int seconds = (int) (totalTime % 60);
System.out.printf("%02d:%02d:%02d\n", hours, minutes, seconds);
}

Use the below code snippet for the while loop you are using
while(faceFinish < startRadius) {
startRadius -= feed; //reduces diameter by feed
rpm = ((sfm * 3.82) / (startRadius * 2))>2000?2000:((sfm * 3.82) / (startRadius * 2));
totalTime += (feed / (feed * rpm)) * 60;
}

Please try below code.
class Rpm{
double value=0.0;
final double LIMIT = 2000.0;
public void setValue(double value){
if(value < LIMIT)
this.value= value;
}
public double getValue(){
return this.value;
}
}
public class yourclassname {
public static void main(String[] args) {
double startRadius = 6; //Radius of stock diameter
double faceFinish = 0;
double feed = .010; //Amount the tool will advance per revolution
double sfm = 200; //Surface speed of tool (Surface feet per minute)
Rpm rpm = new Rpm();
double totalTime = 0;
while(faceFinish < startRadius) {
startRadius -= feed; //reduces diameter by feed
rpm.setValue( (sfm * 3.82) / (startRadius * 2)); //establishes new rpm per tool advance
totalTime += (feed / (feed * rpm.getValue())) * 60;
}
int hours = (int) (totalTime / 3600);
int minutes = (int) ((totalTime % 3600) / 60);
int seconds = (int) (totalTime % 60);
System.out.printf("%02d:%02d:%02d\n", hours, minutes, seconds);
}
}

Related

My code does exactly what it has to do, but i have no idea why

is supposed to calculate the coordinates of a projectile launched with respect to time (steps of 100ms), with a linear equation, and it outputs linear numbers, but if i plot this equation with CalcMe.com (math tool) it makes a parabolic plot
InVel = Double.parseDouble(jTextField1.getText());
g = Double.parseDouble(jTextField8.getText());
y = 1;
while(y >= -1) {
t += 100;
x = InVel * TimeUnit.MILLISECONDS.toSeconds(t) * Math.cos(45);
y = InVel * TimeUnit.MILLISECONDS.toSeconds(t) * Math.sin(45) - (1 / 2) * g * Math.pow(TimeUnit.MILLISECONDS.toSeconds(t), 2);
//System.out.print(Double.toString(x));
//System.out.printf(" ");
System.out.print(Double.toString(y));
System.out.printf("%n");
}
jTextField6.setText(Double.toString(x));
the code is in java
g is constant (9.8)
and invel is given by user so its constant too
g is the gravity and invel the initial velocity of the projectile
the equation is:x=invel*time*cos(45) and y=invel*time*sin(45)-(1/2)*g*t^2
anyone can help me?
Your milisecond to second value conversion method TimeUnit.MILLISECONDS.toSeconds(t) is the main fact. Its returning long value which one you are wanted double. Please take a look on below code. Probably its your answer. Just replace hard-coded value with your jTextField
public static void main(String[] args) {
double InVel = Double.parseDouble("10.555");
double g = Double.parseDouble("9.8");
double y = 1;
double x=0;
double t=0;
while(y >= -1) {
t += 100;
double timeInSeconds = (t / (double)1000) % (double)60;
x = InVel * timeInSeconds * Math.cos(45);
y = InVel * timeInSeconds * Math.sin(45) - ((double) 1 / (double) 2) * g * Math.pow(timeInSeconds, 2);
//System.out.print(Double.toString(x));
//System.out.printf(" ");
System.out.println("X = " + x + " Y = " + Double.toString(y));
System.out.printf("%n");
}
}

my math is broken on TextView

To be honest I've just started with programming but for the life of me I can't figure out where I'm wrong.
the math is:
10$ / 2 hours
tips per hour = 5 (i get 0.2)
waiter 1 pay = 10 (i get 0.4?)
screenshot
The Calculation in MainActivity:
double resultTotalHours = cWaiter1Hours + cWaiter2Hours + cWaiter3Hours + cWaiter4Hours;
double calcTipsPerHour = resultTotalHours / totalTips;
double resultBarsCut = (totalTips * (cBarCutInput / 100));
double resultTaxDeposit = resultTotalHours * 3;
double resultTipsPerHour = (totalTips - resultBarsCut - resultTaxDeposit) / resultTotalHours;
double resultWaiter1Pay = cWaiter1Hours * resultTipsPerHour;
double resultWaiter2Pay = cWaiter2Hours * resultTipsPerHour;
double resultWaiter3Pay = cWaiter3Hours * resultTipsPerHour;
double resultWaiter4Pay = cWaiter4Hours * resultTipsPerHour;
double resultWaiter1NoTax = cWaiter1Hours * calcTipsPerHour;
double resultWaiter2NoTax = cWaiter2Hours * calcTipsPerHour;
double resultWaiter3NoTax = cWaiter3Hours * calcTipsPerHour;
double resultWaiter4NoTax = cWaiter4Hours * calcTipsPerHour;
Casting the results to the TextViews:
if (calcTipsPerHour <= 30) {
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(calcTipsPerHour));
barsCutView.setText(Double.toString(0));
taxDepositView.setText(Double.toString(0));
waiter1Pay.setText(Double.toString(resultWaiter1NoTax));
waiter2Pay.setText(Double.toString(resultWaiter2NoTax));
waiter3Pay.setText(Double.toString(resultWaiter3NoTax));
waiter4Pay.setText(Double.toString(resultWaiter4NoTax));
} else {
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(resultTipsPerHour));
barsCutView.setText(Double.toString(resultBarsCut));
taxDepositView.setText(Double.toString(resultTaxDeposit));
waiter1Pay.setText(Double.toString(resultWaiter1Pay));
waiter2Pay.setText(Double.toString(resultWaiter2Pay));
waiter3Pay.setText(Double.toString(resultWaiter3Pay));
waiter4Pay.setText(Double.toString(resultWaiter4Pay));
}
The problem is here:
double calcTipsPerHour = resultTotalHours / totalTips;
This is currently doing 2 / 10 = 0.2.
You want to do the reciprocal:
double calcTipsPerHour = totalTips / resultTotalHours;
This should also fix your waiter's pay
You put hours in the numerator and tips in the denominator so you are getting the inverse of what you want: hours/tip
What you want is:
double calcTipsPerHour = totalTips / resultTotalHours;

Java Game Loop Help-updates per second vs frames per second

Assuming I use this game loop and want to maintain 60 FPS, what would be the appropriate UPS (updates per second)? Should it be 60 as well? Thanks for any help
#Override
public void run() {
long initialTime = System.nanoTime();
final double timeU = 1000000000 / UPS;
final double timeF = 1000000000 / FPS;
double deltaU = 0, deltaF = 0;
int frames = 0, ticks = 0;
long timer = System.currentTimeMillis();
while (running) {
long currentTime = System.nanoTime();
deltaU += (currentTime - initialTime) / timeU;
deltaF += (currentTime - initialTime) / timeF;
initialTime = currentTime;
if (deltaU >= 1) {
getInput();
update();
ticks++;
deltaU--;
}
if (deltaF >= 1) {
render();
frames++;
deltaF--;
}
if (System.currentTimeMillis() - timer > 1000) {
if (RENDER_TIME) {
System.out.println(String.format("UPS: %s, FPS: %s", ticks, frames));
}
frames = 0;
ticks = 0;
timer += 1000;
}
}
}
Update should be fixed
double previous = getCurrentTime();
double lag = 0.0;
while (true) {
double current = getCurrentTime();
double elapsed = current - previous;
previous = current;
lag += elapsed;
processInput();
while (lag >= MS_PER_UPDATE) {
update();
lag -= MS_PER_UPDATE;
}
render();
}
If the difference between the real time and the game time is higher than wanted time between two updates you have to update.
If lag is lower it means you dont have to update yet but you can render anyway.
Better explanation here: http://gameprogrammingpatterns.com/game-loop.html

Strange issue in converting Feet and Inches to Centimeter and Vice Versa

public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
Above is the function for converting Feet and Inches to Centimeter.Below is the function for converting Centimeter back to Feet and Inches.
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
I have a problem when i enter normal values like 5 Feet and 6 Inches, its converting perfectly to centimeter and again it gets converted back to 5 Feet and 6 Inches.
The Problem is when i convert 1 Feet and 1 inches or 2 Feet and 2
inches, its getting converted back to 1 Feet 2 inches and 2 Feet 3
inches.
I ran the following code
public class FeetInches{
public static void main(String[] args){
double d = convertFeetandInchesToCentimeter("1","1");
String back_again = convertCentimeterToHeight(d);
System.out.println(back_again);
}
public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
System.out.println((d / 2.54) - (feetPart * 12));
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
}
And got
1.0000000000000018
1' 2''
By using the ceiling function you are rounding up to 2 when you really want to be rounding down to 1.
I believe:
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
Should be:
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
The problem is because of the way java handles floating point numbers.
inchesPart = (int) Math.ceil(Math.round((d / 2.54) - (feetPart * 12)));
or
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
In case of input 2,2 the original value of inchesPart is 2.0000000000000036 -> ceil ->3
The main issue with you're code is that you're not using the same rounding function for each part :
int feetPart = (int) Math.floor((d / 2.54) / 12);
^^^^^
int inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
^^^^
You should also do the rounding before the decomposition in order to obtain consistent results :
int feetPart = ((int) Math.round(d / 2.54)) / 12;
int inchesPart = ((int) Math.round((d / 2.54)) - (feetPart * 12);
Which could be factorized to:
int inches = (int) Math.round(d / 2.54);
int feetPart = inches / 12;
int inchesPart = inches - (feetPart * 12);
Or since ( inches - ( ( inches / 12 ) * 12) ) == ( inches % 12 ):
int inches = (int) Math.round(d / 2.54);
feetPart = inches / 12;
inchesPart = inches % 12;
You can interchange Math.round with Math.floor or Math.ceil depending on the result you expect.
I know this is old may be useful for someone else (Kotlin version)
fun feetToCentimeter(feetval: String): String {
var heightInFeet = 0.0
var heightInInches = 0.0
var feet = ""
var inches = ""
if (!TextUtils.isEmpty(feetval)) {
if (feetval.contains("'")) {
feet = feetval.substring(0, feetval.indexOf("'"))
}
if (feetval.contains("\"")) {
inches = feetval.substring(feetval.indexOf("'") + 1, feetval.indexOf("\""))
}
}
try {
if (feet.trim { it <= ' ' }.isNotEmpty()) {
heightInFeet = feet.toDouble()
}
if (inches.trim { it <= ' ' }.isNotEmpty()) {
heightInInches = inches.toDouble()
}
} catch (nfe: NumberFormatException) {
}
return (((heightInFeet * 12.0) + heightInInches) * 2.54).toString()
}
fun centimeterToFeet(centemeter: String?): String {
var feetPart = 0
var inchesPart = 0
if (!TextUtils.isEmpty(centemeter)) {
val dCentimeter = java.lang.Double.valueOf(centemeter!!)
feetPart = Math.floor((dCentimeter / 2.54) / 12).toInt()
println(dCentimeter / 2.54 - feetPart * 12)
inchesPart = Math.floor((dCentimeter / 2.54) - (feetPart * 12)).toInt()
}
return String.format("%d' %d\"", feetPart, inchesPart)
}

Getting millisecond format

I am trying to get this string to return Minute:Second:Millisecond for my MediaPlayer. I have found this code, but can't figure out how to make the Milliseconds work and put it at 2 decimal places. I'm sure its simple to the right person!
private String getTimeString(long millis) {
StringBuffer buf = new StringBuffer();
int hours = (int) (millis / (1000*60*60));
int minutes = (int) (( millis % (1000*60*60) ) / (1000*60));
int seconds = (int) (( ( millis % (1000*60*60) ) % (1000*60) ) / 1000);
buf
.append(String.format("%02d", hours))
.append(":")
.append(String.format("%02d", minutes))
.append(":")
.append(String.format("%02d", seconds));
return buf.toString();
}
Thanks always guys
There are 1000 milliseconds in one second, i.e. you'd need 3 decimal places for the milliseconds:
/** return time in format 1:23.456 */
private String getTimeString(long millis) {
int minutes = (int) (millis / (1000 * 60));
int seconds = (int) ((millis / 1000) % 60);
int milliseconds = (int) (millis % 1000);
String.format("%d:%02d.%03d", minutes, seconds, milliseconds);
}
If you absolutely want 2 digits for milliseconds, you actually get 1/100 seconds and not milliseconds:
/** return time in format 1:23.45 */
private String getTimeString(long millis) {
int minutes = (int) (millis / (1000 * 60));
int seconds = (int) ((millis / 1000) % 60);
int seconds100 = (int) ((millis / 10) % 100);
String.format("%d:%02d.%02d", minutes, seconds, seconds100);
}
However, a common display format for media players is to use one digit for 10ths of seconds:
/** return time in format 1:23.4 */
private String getTimeString(long millis) {
int minutes = (int) (millis / (1000 * 60));
int seconds = (int) ((millis / 1000) % 60);
int seconds10 = (int) ((millis / 100) % 10);
String.format("%d:%02d.%d", minutes, seconds, seconds10);
}
If you want to put the milliseconds at two decimal places, keep in mind that you will only be able to show increments of 10ms; 1ms = 0.001s, three decimal places. But regardless, the code you are looking for is:
int rem_milliseconds = (int)(millis % 1000); // Remaining ms after last second
...
.append(String.format("%02d", rem_milliseconds));
I left it at 2 decimal places.
Try this:
private String getTimeString(long millis) {
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
millis -= TimeUnit.MINUTES.toMillis(minutes) + TimeUnit.SECONDS.toMillis(seconds);
return String.format("%d:%d:%d", minutes, seconds, millis);
}

Categories