So I have a piece of code where I want to output the seconds as an integer, but I don't want to lose the decimal value as I need to use it as part of the count in a for loop to code the program correctly, here is the code (for loop is unfinished obviously as there is no count)
System.out.println("Recommended Splits for Marathon for time of "
+ hours + ":" + minutes + ":" + seconds);
hoursInSeconds = hours * 3600;
minutesInSeconds = minutes * 60;
totalTime = hoursInSeconds + minutesInSeconds + seconds;
double totalSecondsPerKM = totalTime/42;
int hoursPerKM = (int) (totalSecondsPerKM/3600);
double remainderHours = totalSecondsPerKM%3600;
int minutesPerKM = (int) (totalSecondsPerKM/60);
double secondsPerKM = (totalSecondsPerKM%60);
for (int index = 1; index <=42; index++){
System.out.print(index + " ");
System.out.print("" +hoursPerKM);
System.out.print("");
System.out.print(":"+minutesPerKM);
System.out.print("");
System.out.print(":"+secondsPerKM);
System.out.println("");
You could use
System.out.println(String.format("%.0f", 1.6));
or
System.out.println((int)1.6);
The first will round the value, output 2, the second will truncate it, outputting 1
Related
I need to select a value based on a percentage chance of that value being selected. For example:
10% of the time increment value a
20% of the time increment value b
30% of the time increment value c
40% of the time increment value d
The percentages will always add up to exactly 100%
I have encountered several solutions like this one, but have determined that they cannot possibly be correct. Here is a sample program built using the solution mentioned:
import java.util.Random;
public class Main {
private static Random r = new Random();
public static void main(String[] args) {
final int iterations = 1000000;
System.out.println("Testing percentage based random, " + iterations + " iterations");
int onePercent = 0;
int sixPercent = 0;
int sevenPercent = 0;
int thirtySixPercent = 0;
int fiftyPercent = 0;
// Those values add up to 100% overall
for (int i = 0; i < iterations; i++) {
int random = r.nextInt(100);
if (random < 1) {
onePercent++;
continue;
}
if (random < 6) {
sixPercent++;
continue;
}
if (random < 7) {
sevenPercent++;
continue;
}
if (random < 36) {
thirtySixPercent++;
continue;
}
if (random < 50) {
fiftyPercent++;
continue;
}
// That can't be right because if random > 50 then nothing at all happens
}
System.out.println("One percent happened about " + (onePercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Six percent happened about " + (sixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Seven percent happened about " + (sevenPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Thirty six percent happened about " + (thirtySixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Fifty percent happened about " + (fiftyPercent / Float.valueOf(iterations)) * 100 + "% of the time");
}
}
Output:
Testing percentage based random, 1000000 iterations
One percent happened about 0.99649996% of the time
Six percent happened about 4.9925% of the time
Seven percent happened about 1.0029999% of the time
Thirty six percent happened about 29.001299% of the time
Fifty percent happened about 14.0191% of the time
Expected output:
Testing percentage based random, 1000000 iterations
One percent happened about 0.99649996% of the time
Six percent happened about 6.9925% of the time
Seven percent happened about 7.0029999% of the time
Thirty six percent happened about 36.001299% of the time
Fifty percent happened about 50.0191% of the time
I believe I need to use some sort of algorithm to convert the percentages into a scale from 0 to 99 so that the random number generator can select a value accurately. I cannot think of how to do that, though.
Your results are correct :
Fifty percent happened about 14.0191% of the time
50 - 36 = 14
Thirty six percent happened about 29.001299% of the time
36 - 7 = 29
Seven percent happened about 1.0029999% of the time
7 - 6 = 1
....
Delete all 'continue' statements if you want them to sum up.
Figured it out. You need to keep track of the percentage tested so far and add it to the current test.
import java.util.Random;
public class Main {
private static Random r = new Random();
public static void main(String[] args) {
final int iterations = 1000000;
System.out.println("Testing percentage based random, " + iterations + " iterations");
int onePercent = 0;
int sixPercent = 0;
int sevenPercent = 0;
int thirtySixPercent = 0;
int fiftyPercent = 0;
// Those values add up to 100% overall
for (int i = 0; i < iterations; i++) {
int random = r.nextInt(100);
int totalPercent = 0;
if (random < totalPercent + 1) {
onePercent++;
continue;
}
totalPercent += 1;
if (random < totalPercent + 6) {
sixPercent++;
continue;
}
totalPercent += 6;
if (random < totalPercent + 7) {
sevenPercent++;
continue;
}
totalPercent += 7;
if (random < totalPercent + 36) {
thirtySixPercent++;
continue;
}
totalPercent += 36;
if (random < totalPercent + 50) {
fiftyPercent++;
continue;
}
totalPercent += 50;
// That can't be right because if random > 50 then nothing at all happens
}
System.out.println("One percent happened about " + (onePercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Six percent happened about " + (sixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Seven percent happened about " + (sevenPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Thirty six percent happened about " + (thirtySixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Fifty percent happened about " + (fiftyPercent / Float.valueOf(iterations)) * 100 + "% of the time");
}
}
This question already has answers here:
Java - Looping 2d Array to find index of a value not working
(2 answers)
Closed 7 years ago.
I'm learning java atm , and had to write a code to calculate the monetary units, and only display the nonzero denominations using singular words for single units and plural words for plural units.
This is the code so far:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
// receive amount
System.out.println("Enter an amount in double, for example 11.56: ");
double amount = input.nextDouble();
int remainingAmount = (int)(amount * 100);
// find the number of one dollars
int numberOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// find the number of quarters in the remaing amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
//find the number of dimes in the remaing amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
//find the number of nickels in the remaing amount
int numberOfNickles = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
//find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
//Display results
System.out.println("Your amount" + amount + "consists of");
if (numberOfDollars > 1) {
System.out.println(" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1); {
System.out.println(" " + numberOfDollars + "dollar");
}
The output is:
run:
Enter an amount in double, for example 11.56:
12,33
Your amount12.33consists of
12dollars
12dollar
1quarters
1quarter
0dimes
0dime
1nickles
1nickle
3pennies
3penny
Why is everything printed double? 3 == not 1 so why does it still say 3 penny?
Noob question maybe, but thats because i am one :) Thanks for help!
Because you added a random ; after the second if. Therefor your second System.out.println is not part of the if-statement. Remove it:
if (numberOfDollars > 1) {
System.out.println (" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1) {
System.out.println (" " + numberOfDollars + "dollar");
}
Remove the semicolon after if();
if (numberOfDollars == 1);
The second print statement is printing because it is not a part of if(); due to the semicolon that you have after if()
replace
else if (numberOfDollars == 1); { // with ;, condition terminates here itself
with
else if (numberOfDollars == 1) {
Semicolon at the end of If statememnt , finish the statement in single line. Means it ignores the result of condition and continue the execution from the next line.
Java input;
import java.util.*;
public class NetPay3
{
public static void main()
{
// Define Scanner object
Scanner inLine = new Scanner (System.in);
// Define other variables
float pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds,
OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
// Ask for the time in seconds
System.out.print ("Enter Net Pay : ");
pay = inLine.nextFloat();
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OneHundredPounds = (int) pay / 100;
// Calculate what is left over and store back into seconds
pay = pay % 100;
// Calculate the minutes. There are 60 seconds
// in a minute.
FiftyPounds = (int) pay / 50;
// Whatever is left over must be the seconds
pay = pay % 50;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
TwentyPounds = (int) pay / 20;
// Calculate what is left over and store back into seconds
pay = pay % 20;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FivePounds = (int) pay / 5;
// Calculate what is left over and store back into seconds
pay = pay % 5;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OnePound = (int) pay / 1;
// Calculate what is left over and store back into seconds
pay = pay % 1;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FiftyPence = (int) pay / 2;
// Calculate what is left over and store back into seconds
pay = pay % 2;
// Display the hours, minutes and seconds
System.out.println ("Amount of £100 notes " + OneHundredPounds);
System.out.println ("Amount of £50 notes " + FiftyPounds);
System.out.println ("Amount of £20 notes " + TwentyPounds);
System.out.println ("Amount of £5 notes " + FivePounds);
System.out.println ("Amount of £1 coins " + OnePound);
System.out.println ("Amount of 50p coins " + FiftyPence);
}
}
Screen input and output;
Enter Net Pay : 176.50
Amount of £100 notes 1
Amount of £50 notes 1
Amount of £20 notes 1
Amount of £5 notes 1
Amount of £1 coins 1
Amount of 50p coins 0
Hi relatively new to programming,
having trouble with me modulus and int operators in terms of getting them to function with the correct output on screen, previous syntax's worked correctly bar the 50p, anyone care to shed any light? thanks :)
Try changing FiftyPence = (int) pay / 2; toFiftyPence = (int) (pay / 0.5f);
Here is your code corrected and improved.
Don't use floats here, use integer arithmetic.
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
// Define Scanner object
Scanner inLine = new Scanner(System.in);
// Define other variables
int pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds, OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
OneHundredPounds = (int) pay / 10000;
pay = pay % 10000;
FiftyPounds = (int) pay / 5000;
pay = pay % 5000;
TwentyPounds = (int) pay / 2000;
pay = pay % 2000;
FivePounds = (int) pay / 500;
pay = pay % 500;
OnePound = (int) pay / 100;
pay = pay % 100;
FiftyPence = (int) pay / 50;
pay = pay % 50;
System.out.println("Amount of £100 notes " + OneHundredPounds);
System.out.println("Amount of £50 notes " + FiftyPounds);
System.out.println("Amount of £20 notes " + TwentyPounds);
System.out.println("Amount of £5 notes " + FivePounds);
System.out.println("Amount of £1 coins " + OnePound);
System.out.println("Amount of 50p coins " + FiftyPence);
System.out.println("Leftover pence: " + pay);
}
}
But I would further simplify this to (for example) this program:
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
Scanner inLine = new Scanner(System.in);
float[] val = new float[]{100, 50, 20, 5, 1, 0.5f, 0.2f, 0.05f, 0.02f, 0.01f};
int pay;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
for (int i=0; i<val.length; i++){
int m = ((int)(val[i] * 100));
int cnt = pay / m;
String s1 = val[i] < 1 ? " coins: " : " notes: ";
String s2 = val[i] < 1 ? "" : "£";
String s3 = val[i] < 1 ? "p" : "";
String s4 = val[i] < 1 ? m + "" : (m/100) + "";
System.out.println("Amount of " + s2 + s4 + s3 + s1 + cnt);
pay = pay % m;
}
}
}
Right now I am finding out 25% of a persons years and for example if you had 5 years 25% is 1.25. Though the plugin im making cant remove 1.25 years from you the .25 needs to be converted to weeks and then any leftovers to days and so on. Though I dont know how I would convert these times.
Integer y = itapi.getPlayerYears(player.getName());
Double yremove = Integer.valueOf(y) * 0.25;
Integer w = itapi.getPlayerWeeks(player.getName());
Double wremove = Integer.valueOf(w) * 0.25;
Integer d = itapi.getPlayerDays(player.getName());
Double dremove = Integer.valueOf(d) * 0.25;
Integer h = itapi.getPlayerHours(player.getName());
Double hremove = Integer.valueOf(h) * 0.25;
Integer m = itapi.getPlayerMinutes(player.getName());
Double mremove = Integer.valueOf(m) * 0.25;
Integer s = itapi.getPlayerSeconds(player.getName());
Double sremove = Integer.valueOf(s) * 0.25;
String yminus = String.valueOf(yremove) + 'y';
String wminus = String.valueOf(wremove) + 'w';
String dminus = String.valueOf(dremove) + 'd';
String hminus = String.valueOf(hremove) + 'h';
String mminus = String.valueOf(mremove) + 'm';
String sminus = String.valueOf(sremove) + 's';
ItemStack book = itapi.createTimeCard("Death of " + player.getName(), yminus + wminus + dminus + hminus + mminus + sminus, 1);
itapi.removeTime(player.getName(), yminus + wminus + dminus + hminus + mminus + sminus );
e.getDrops().add(book);
Would it be possible to work the conversion out or would it be better to convert all time to seconds then take 25% and convert it back?
I would use nested ifs and pass the remainder around. I have not tested this but it should give you an idea.
Integer y = itapi.getPlayerYears(player.getName());
double yremove = Integer.valueOf(y) *0.25;
double numWeeks = yremove * 52; //returns the number in weeks
double numDays =0;
double numHours =0;
double numMinutes =0;
double numSeconds =0;
if(numWeeks % 52 != 0){
numDays = (numWeeks % 52) * 7;
if(numDays % 7 !=0){
numHours = (numDays % 7) * 24;
if(numHours % 24 !=0){
numMinutes = (numHours % 24) * 60;
if(numMinutes % 60 !=0){
numSeconds = (numMinutes % 60) * 60;
}
}
}
}
//... then convert to string as you are already doing and pass it to removeTime()
You can use Calendar class to calculate this for you, something like:
Calendar c = Calendar.getInstance();
double millis = 1.25 * 31557600 * 1000;
long l = (long) millis;
c.setTimeInMillis(l);
System.out.println(c.get(Calendar.YEAR) + " Year");
System.out.println(c.get(Calendar.MONTH) + " months");
System.out.println(c.get(Calendar.WEEK_OF_MONTH) + " weeks");
System.out.println(c.get(Calendar.DAY_OF_MONTH) + " days");
System.out.println(c.get(Calendar.HOUR) + " hours");
System.out.println(c.get(Calendar.MINUTE) + " minutes");
System.out.println(c.get(Calendar.SECOND) + " seconds");
Output:
1971 Year
3 months
1 weeks
2 days
7 hours
0 minutes
0 seconds
Calendar defaults the starting year to 1970, you can further manipulate year and months to weeks if need be.
Create a class to manage time. This class will have methods to return time in terms of years, weeks, months, etc.
public class Time{
private long milliseconds;
public double getSeconds(){
double seconds = milliseconds/1000.0;
return seconds;
}
public void subtractSeconds(double seconds){
long millisInSeconds = (long)(seconds*1000);
this.millisecionds -= millisInSeconds;
}
//write more methods for years, months etc.
}
Then, use this class to retrieve years, months, weeks and subtract the difference. This will keep your code clean, and easy to understand.
Time time = new Time(1000*60*60);
int years = (int)time.getYears();
time.subtractYears(years);
int months = (int)time.getMonths();
time.subtractMonths(months);
I wrote a programm to get the cross sum of a number:
So when i type in 3457 for example it should output 3 + 4 + 5 + 7. But somehow my logik wont work. When i type in 68768 for example i get 6 + 0 + 7. But when i type in 97999 i get the correct output 9 + 7 + 9. I know that i have could do this task easily with diffrent methods but i tried to use loops . Here is my code: And thanks to all
import Prog1Tools.IOTools;
public class Aufgabe {
public static void main(String[] args){
System.out.print("Please type in a number: ");
int zahl = IOTools.readInteger();
int ten_thousand = 0;
int thousand = 0;
int hundret = 0;
for(int i = 0; i < 10; i++){
if((zahl / 10000) == i){
ten_thousand = i;
zahl = zahl - (ten_thousand * 10000);
}
for(int f = 0; f < 10; f++){
if((zahl / 1000) == f){
thousand = f;
zahl = zahl - (thousand * 1000);
}
for(int z = 0; z < 10; z++){
if((zahl / 100) == z){
hundret = z;
}
}
}
}
System.out.println( ten_thousand + " + " + thousand + " + " + hundret);
}
}
Is this what you want?
String s = Integer.toString(zahl);
for (int i = 0; i < s.length() - 1; i++) {
System.out.println(s.charAt(i) + " + ");
}
System.out.println(s.charAt(s.length()-1);
The problem with the code you've presented is that you have the inner loops nested. Instead, you should finish iterating over each loop before starting with the next one.
What's happening at the moment with 68768 is when the outer for loop gets to i=6, the ten_thousand term gets set to 6 and the inner loops proceed to the calculation of the 'thousand' and 'hundred' terms - and does set those as you expect (and leaving zahl equal to 768 - notice that you don't decrease zahl at the hundreds stage)
But then the outer loop continues looping, this time with i=7. With zahl=768, zahl/1000 = 0' so the 'thousand' term gets set to 0. The hundred term always gets reset to 7 with zahl=768.
The 97999 works because the thousand term is set on the final iteration of the 'i' loop, so never gets reset.
The remedy is to not nest the inner loops - and it'll perform a lot better too!
You should do something like this
input = 56789;
int sum = 0;
int remainder = input % 10 // = 9;
sum += remainder // now sum is sum + remainder
input /= 10; // this makes the input 5678
...
// repeat the process
To loop it, use a while loop instead of a for loop. This a great example of when to use a while loop. If this is for a class, it will show your understanding of when to use while loops: when the number of iterations is unknown, but is based on a condition.
int sum = 0;
while (input/10 != 0) {
int remainder = input % 10;
sum += remainder;
input /= 10;
}
// this is all you really need
Your sample is a little bit complicated. To extract the tenthousand, thousand and the hundreds you can simply do this:
private void testFunction(int zahl) {
int tenThousand = (zahl / 10000) % 10;
int thousand = (zahl / 1000) % 10;
int hundred = (zahl / 100) % 10;
System.out.println(tenThousand + "+" + thousand + "+" + hundred);
}
Bit as many devs reported you should convert it to string and process character by character.