简体   繁体   中英

Calculate a value to update JProgressBar

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 (ie both set to 50 as well). When I subtract any number from intPlayer1Tickets or intPlayer2Tickets (eg 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM