I would like to display the proportion of an initial value in a JProgressBar.
private void updateProgressBars() { //Update the progress bars to the new values.
int p1 = 0, p2 = 1; //Player numbers
double p1Progress = (intPlayer1Tickets/intInitialPlayer1Tickets) * 100;
double p2Progress = (intPlayer2Tickets/intInitialPlayer2Tickets) * 100;
progressbarPlayerTickets[p1].setValue((int) p1Progress);
progressbarPlayerTickets[p1].setString("Tickets left: " + Integer.toString(intPlayer1Tickets));
progressbarPlayerTickets[p2].setValue((int) p2Progress);
progressbarPlayerTickets[p2].setString("Tickets left: " + Integer.toString(intPlayer2Tickets));
}
In this code, the intention was to calculate the percentage of the amount of tickets left a player has. intInitialPlayer1Tickets and intInitialPlayer2Tickets were both set to 50. intPlayer1Tickets and intPlayer2Tickets were then set to their respective initial tickets value (i.e. both set to 50 as well). When I subtract any number from intPlayer1Tickets or intPlayer2Tickets (e.g. intPlayer1Tickets = 49, intInitialPlayer1Tickets = 50), their respective progress bars' value would be set to 0, which is not my intention. Both progress bars have their min and max values set to 0 and 100.
So how would I make it so it would reflect the proportion of tickets left as a percentage?
You are doing integer math and then converting it to a double. In integer math when you divide a number with a number that is bigger, the answer is always 0.
You want to get Java to do your math with floating point numbers rather than with integers. The easiest way to do this is to make your divisor a double.
When you run this code
public class Numbers{
public static void main(String []args){
int five = 5;
int ten = 10;
System.out.println(five/ten);
System.out.println(five/(double)ten);
System.out.println((five/(double)ten)*100);
}
}
You get this as the output
0
0.5
50.0
So, to answer your question what you want is something like this
double p1Progress = (intPlayer1Tickets/(double)intInitialPlayer1Tickets) * 100;
But you'd be just fine using float for this instead of doubles.
Cast the value of intPlayer1Tickets, intPlayer2Tickets, intInitialPlayer1Tickets and intInitialPlayer2Tickets to double before you calculate. As in:
double p1Progress = (((double) intPlayer1Tickets)/((double) intInitialPlayer1Tickets)) * 100;
double p2Progress = (((double) intPlayer2Tickets)/((double) intInitialPlayer2Tickets)) * 100;
Related
For my cash register simulation, I have to take the change due and print it out in terms of 100s, 50s, 20s, 10s, 5s, 1s, and ofcourse change. I have two questions that I'm struggling with:
1.) Is there an easier way to figure out how many dollar bills are needed for each one if any? My equations work but it' s long and I think there's an easier way to do it?
2.) When dealing with cents is am i supposed to do (changeDue%100)?
changeDue is equal to 39.12 and I'm trying to pull of just the 12 cents, but I dont quite know how? Can someone please help explain to me?
double changeDue = 39.12;
double coins;
double change;
int hundreds;
int fifties;
int twenties;
int tens;
int fives;
int ones;
int quarters;
int dimes;
int nickels;
int pennies;
double cents;
//calculations for amount of each dollar bill that needs to be given back
hundreds = (int)(changeDue/100);
change = changeDue - (hundreds * 100);
fifties = (int)(change/50);
change = changeDue - (hundreds * 100) - (fifties * 50);
twenties = (int)(change/20);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20);
tens = (int)(change/10);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20) - (tens * 10);
fives = (int)(change/5);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20) - (tens * 10) - ( fives * 5);
ones = (int)(change/1);
//calculations for amount of coins that needs to be given back
cents = changeDue%100;
quarters = (int)cents/10;
The modulus operator gives the remainder after division. In your example changeDue % 100 divides the number by 100 and returns the remainder. If you provide the number in pennies, say 3912, then this will work exactly as you expect. However, you are using dollars instead. So first convert the dollar amount to pennies by multiplying by 100.
Note
ones = (int)(change/1); can be simplified to ones = (int) change;.
Another method to derive change less than a dollar is:
cents=changeDue-(int)changeDue
1.) Is there an easier way to figure out how many dollar bills are needed for each one if any? My equations work but it' s long and I think there's an easier way to do it?
I have found an easier way for your calculations. Refer to the code and code comments below.
public static void main(String args[]) {
double changeDue = 39.12; // The change needed
double change = changeDue; // Used for the calculations of change
/*
* Add here possible change, use an array so that you won't have to declare many
* variables This way if you want to add other possible changes you just have to
* add it in the array But make sure the possible changes is arrange in
* descending order
*/
double[] possibleChange = new double[] { 100, 50, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01 }; // the possible changes
String[] possibleChangeLabel = new String[] { "Hundreds", "Fifties", "Twenties", "Tens", "Fives", "Ones", "Quarters", "Dimes", "Nickels", "Pennies" }; // used for printing
int[] coins = new int[possibleChange.length]; // Used for the number of coins needed for each possible change
/*
* Loop through all the possible changes and acquire the possible number of
* coins needed for each change
*/
for (int i = 0; i < possibleChange.length; i++) {
coins[i] = (int) (change / possibleChange[i]); // calculate the possible number of coins in the given change
change = (double) Math.round((change - (coins[i] * possibleChange[i])) * 100) / 100; // Update the change and limit to 2 decimal places
}
/*
* This is for printing
*/
System.out.println("Your change is $" + changeDue);
System.out.println("The change is composed of: ");
for (int i = 0; i < possibleChange.length; i++) {
if (coins[i] > 0) {
System.out.println( "\t" + coins[i] + " piece/s of $" + possibleChange[i] + "(" + possibleChangeLabel[i] + ")");
}
}
}
2.) When dealing with cents is am i supposed to do (changeDue%100)? changeDue is equal to 39.12 and I'm trying to pull of just the 12 cents, but I dont quite know how? Can someone please help explain to me?
I don't know why you are needing this process, but you can try my code below.
double number = 123.45; // Your change
int decimal = (int) number; // You will get the whole number part (123)
double fractional = number - decimal; // You will get the fraction part (45)
I'm new to programming GUI in Java. My code is simple and only needs to do some basic arithmetic but for some reason it's not working. I don't know that I'm using the String.valueOf()correctly.
My code:
String restaurantName;
double subTotal = 0;
int tipPercentage = 0;
double totalBill = 0;
double tipInDollars = 0;
restaurantName = txtRestaurantName.getText();
subTotal = Double.parseDouble(txtSubtotal.getText());
tipPercentage = Integer.parseInt(txtTipAmt.getText());
tipInDollars = ((tipPercentage / 100) * subTotal);
totalBill = (tipInDollars + subTotal);
lblDisplayTip.setText(String.valueOf(tipPercentage) + "%");
lblDisplayTotalBill.setText(String.valueOf(totalBill));
If the user enters 50 for subtotal and 10 for the tip percentage, I would expect tipInDollars to equal 5 and for totalBill to equal 55.
Yet the output is:
Your issue is not with your display, it's with your calculation, or rather, the variables you use for your calculation. You can either make tipPercentage a double, or you can make the 100 in this line: tipInDollars = ((tipPercentage / 100) * subTotal); into 100.0. Either solution should fix your problem.
The problem arises from dividing an integer (tipPercentage) by another integer (100). When you do this, Java will round down and always make your result 0.
Within my Activity I am attempting to divide two values then multiply them by 100 in order to give a percentage score.
My issue is that the percentage score is always zero, even though this is impossible with the values I am using.
What am I doing wrong?
Declaring the 2 variables at start of activity:
int score = 0;
int totalQuestions=0;
Onclick logic showing how they are calculated:
public void onClick(View v) {
if (checkForMatch((Button) v)) {
//increment no of questions answered (for % score)
totalQuestions++;
//increment score by 1
score++;
} else {
//increment no of questions answered (for % score)
totalQuestions++;
}
}
public void writeToDatabase() {
// create instance of databasehelper class
DatabaseHelper db = new DatabaseHelper(this);
int divide = (score/ totalQuestions );
int percentageScore = (divide * 100);
Log.d("Pertrace", "per score "+ percentageScore);
Log.d("divide", "divide "+ divide);
// Adding the new Session to the database
db.addScore(new Session(sessionID, "Stroop", SignInActivity
.getUserName(), averageMedLevel, medMax, averageAttLevel,
attMax, percentageScore, myDate, "false", fileNameRaw, fileNameEEGPower, fileNameMeditation, fileNameAttention));
// single score, used for passing to next activity
single = db.getScore(sessionID);
}
Note: from my Trace logs i can see that is it the int divide that is zero, why would this be the case considering that score and totalQuestions are always greater than zero? E.g. 20 and 25.
The reason is this line
int divide = (score/ totalQuestions);
You are dividing the numbers and storing in an int.
You need to store in a double
double divide = (double)score / totalQuestions;
If you want the result as int
double divide = (double)score / totalQuestions;
int percentageScore = (int) Math.ceil(divide * 100);
You are saving them in int. Save values in float or double.
Also, when division occurs, the intermediate result is saved in one of the variable that is used in division. If that is an int, it will be truncated before being saved in double. So do something like double divide = (double)score * totalQuestions
You are performing integer division. First cast score to a double (so you get floating point math), then I would use Math.round() to round the result of the multiplication. For example,
int score = 3;
int totalQuestions = 4;
double divide = ((double) score / totalQuestions);
int percentageScore = (int) Math.round(divide * 100);
System.out.println(percentageScore);
Output is the expected
75
The operands need to be float or double, and so does the variable you put it in:
double divide = (double) score/ totalQuestions;
So basically, I have a variable, time, and would like the program to print the other values for every full second.
For example if I plug in 100, it should print out 20 seconds only.
import java.util.Scanner;
public class CannonBlaster {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
final double DELTA_T = 0.01; //initiating all variables
final double G = 9.81;
double s = 0.0;
double time = 0.0;
double second = 0;
System.out.println("What's the initial velocity?: ");//asking for the initial velocity
double v =input.nextDouble();
while (s >= 0.0) //while loop is used. As long as the height isn't negative it will continue to go.
{
s += v * DELTA_T; //demonstrates the change of velocity and position for every .01 second.
v -= G * DELTA_T;
time += DELTA_T;
System.out.println("The time is: "+time+" "+(double) Math.floor(time)+" "+Math.round(time * 1000) / 1000);
second=Math.round(time * 1) / 1;
if ((double) Math.floor(time) ==time)
{
System.out.println("Approximated position: "+ s);
System.out.println("Formula's position: "+(100.0 * time - (time*time * G) / 2.0)); //prints out the formula values and the loop values.
}
}
}
Excuse the mess, it's just I've been trying different ways to get to work, but found none so far.
The problem is that double doesn't have the kind of accuracy you're looking for, so it doesn't count by an even .01 each iteration as your output clearly shows. The solution is to use BigDecimal. I rewrote the program a bit...
package test;
import java.math.BigDecimal;
import java.util.Scanner;
public class CannonBlaster {
private static final double G = 9.81;
private static final BigDecimal DELTA_T = new BigDecimal(0.01);
private static final double DELTA_T_DOUBLE = DELTA_T.doubleValue();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s = 0.0;
BigDecimal time = new BigDecimal(0.0);
double time_double = 0.0;
System.out.println("What's the initial velocity?: ");// asking for the
// initial
// velocity
double v = input.nextDouble();
// As long as the height isn't negative it will continue to go.
while (s >= 0.0)
{
s += v * DELTA_T_DOUBLE;
v -= G * DELTA_T_DOUBLE;
time = time.add(DELTA_T);
time_double = time.doubleValue();
if (time.doubleValue()%1==0) {
System.out.printf("Approximated position at t=%3ds is %10.6f.\n", time.intValue(), s);
// prints out the formula values and the loop values.
System.out.println("Formula's position: " + formula(time_double));
}
}
}
private static double formula(double x){
return 100.0 * x - (x * x * G) / 2.0;
}
}
The problem is that your time step, DELTA_T, is not exactly representable as a double value. Each iteration accumulates this small error, and you can see this in the time values that get printed out.
Usually it's preferable to avoid this problem when comparing two floating point numbers by comparing the absolute difference between the two numbers to some "small" value, where "small" is defined by the problem / magnitude of numbers you are working with. DELTA_T fits pretty well here, so you could use this comparison for a per-second time step:
if (Math.abs(time - Math.round(time)) < DELTA_T)
{
// Other code here
}
Alternatively, for a more generalized time step, in PRINT_INTERVAL:
final double PRINT_INTERVAL = 0.1;
// Other code...
if (Math.abs(time / PRINT_INTERVAL - Math.round(time / PRINT_INTERVAL)) < DELTA_T)
{
// Other code here
}
I have two doubles like the following
double min = 100;
double max = 101;
and with a random generator, I need to create a double value between the range of min and max.
Random r = new Random();
r.nextDouble();
but there is nothing here where we can specify the range.
To generate a random value between rangeMin and rangeMax:
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
This question was asked before Java 7 release but now, there is another possible way using Java 7 (and above) API:
double random = ThreadLocalRandom.current().nextDouble(min, max);
nextDouble will return a pseudorandom double value between the minimum (inclusive) and the maximum (exclusive). The bounds are not necessarily int, and can be double.
Use this:
double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));
System.out.println(result);
EDIT:
new Random().nextDouble(): randomly generates a number between 0 and 1.
start: start number, to shift number "to the right"
end - start: interval. Random gives you from 0% to 100% of this number, because random gives you a number from 0 to 1.
EDIT 2:
Tks #daniel and #aaa bbb. My first answer was wrong.
import java.util.Random;
public class MyClass {
public static void main(String args[]) {
Double min = 0.0; // Set To Your Desired Min Value
Double max = 10.0; // Set To Your Desired Max Value
double x = (Math.random() * ((max - min) + 1)) + min; // This Will Create A Random Number Inbetween Your Min And Max.
double xrounded = Math.round(x * 100.0) / 100.0; // Creates Answer To The Nearest 100 th, You Can Modify This To Change How It Rounds.
System.out.println(xrounded); // This Will Now Print Out The Rounded, Random Number.
}
}
Hope, this might help the best : Random Number Generators in Java
Sharing a Complete Program:
import java.util.Random;
public class SecondSplitExample
{
public static void main(String []arguments)
{
int minValue = 20, maxValue=20000;
Random theRandom = new Random();
double theRandomValue = 0.0;
// Checking for a valid range-
if( Double.valueOf(maxValue - minValue).isInfinite() == false )
theRandomValue = minValue + (maxValue - minValue) * theRandom.nextDouble();
System.out.println("Double Random Number between ("+ minValue +","+ maxValue +") = "+ theRandomValue);
}
}
Here is the output of 3 runs:
Code>java SecondSplitExample
Double Random Number between (20,20000) = 2808.2426532469476
Code>java SecondSplitExample
Double Random Number between (20,20000) = 1929.557668284786
Code>java SecondSplitExample
Double Random Number between (20,20000) = 13254.575289900251
Learn More:
Top 4 ways to Generate Random Numbers In Java
Random:Docs
Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
//do
}
The main idea of random is that it returns a pseudorandom value.
There is no such thing as fully random functions, hence, 2 Random instances using the same seed will return the same value in certain conditions.
It is a good practice to first view the function doc in order to understand it
(https://docs.oracle.com/javase/8/docs/api/java/util/Random.html)
Now that we understand that the returned value of the function nextDouble() is a pseudorandom value between 0.0 and 1.0 we can use it to our advantage.
For creating a random number between A and B givin' that the boundaries are valid (A>B) we need to:
1. find the range between A and B so we can know how to many "steps" we have.
2. use the random function to determine how many steps to take (because the returned value is between 0.0 and 1.0 you can think of it as "pick a random percentage of increase"
3. add the offset
After all of that, you can see that mob gave you the easiest and most common way to do so in my opinion
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
double RandomValue = Offset + (Range)*(randomVal between 0.0-1.0)