int wordpercent = ((count/totalwords)*100);
                    JOptionPane.showMessageDialog(null, "Count: " + count);
                    JOptionPane.showMessageDialog(null, "Words: " + totalwords);
                    JOptionPane.showMessageDialog(null, "Character Count: " + length);
                    JOptionPane.showMessageDialog(null, previousletter);
                    JOptionPane.showMessageDialog(null, nextletter );
                    JOptionPane.showMessageDialog(null, "Your word makes up " + wordpercent + "% of the document");

This is the final part of my program code. The program lets you select a text file as well as a word and then shows various statistics like the total amount of words in the document, how many times your selected word shows up, etc. My problem is that I want it to show how much of a percentage of the document is made up from your selected word. I am using "int wordpercent = ((count/totalwords)*100); to show that. However, when I run the program everything works perfectly, except for this. It shows up as 0, which doesn't make sense to me since the count and totalwords variables are showing up correctly and are never 0.

Recommended Answers

All 5 Replies

I'm willing to be that count and totalwords are both int too, which means your division is performed in integer context. If the division results in a value less than zero, the precision is ignored and the result will be 0. You want something more like this:

int wordpercent = (int)((count / (double)totalwords) * 100)

This forces the division into floating point context, which retains precision so that it isn't lost before the multiplication step.

It's integer arithmetic, performed in integers throughout.
eg (10/20)x100
10/20 in integer = 0 - there's no fractions in integer values
0x100 = 0

on the other hand
(10x100)/20
10x100 = 1000
1000/20 = 50

That was the problem, thank you guys. I'm new to java and programming in general. I changed "int totalwords" to "double totalwords". The only minor problem I have now is that because I changed totalwords to a double it displays "Total Words: 340.0". Is there any way to make it not display the .0?

Using a double is a valid solution, but it does have side effects. Personally I would just rearrange the expression so it does the multiply before the divide and keep all the variables as ints.
int wordpercent = (count*100)/totalwords;

Thanks, that makes it look a little more clean.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.