Percentage always equal to 0 [duplicate] - java

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 9 years ago.
I have this method. It basically uses popup windows to display simple addition questions:
public static void addition ()
{
JFrame frame = new JFrame("");
JOptionPane.showMessageDialog(frame, "++ You chose Addition! ++");
double percentage;
String rank = "";
int i = 0;
int x = 0;
int y = 0;
while (true){
int add1 = (int)(Math.random()*9) + 1;
int add2 = (int)(Math.random()*9) + 1;
i = i + 1;
int addtotal = add1 + add2;
try{
String test = JOptionPane.showInputDialog(frame, i + "). What's " + add1 + " + " + add2 + "?");
if (test == null){
choose();
}
int convertToNum = Integer.parseInt (test);
if (convertToNum == addtotal){ // if the user got it right
x++;
final ImageIcon icon = new ImageIcon(new URL("http://cdn2.iconfinder.com/data/icons/basicset/tick_64.png")); //Custom Icon for the JFrame below, The image destination uses a URL link to show the icon
JOptionPane.showMessageDialog(null, "Nice Job!\nYou Currently Got " + x + " Out of " + i + " Correct!",":D",JOptionPane.INFORMATION_MESSAGE,icon);
}
else { // if the user got it wrong
JOptionPane.showMessageDialog(frame, "Sorry, but that was wrong.\n" + add1 + " + " + add2 + " = " + addtotal + " . \n You Currently Got " + x + " Out of " + i + " Correct!","Whoops",JOptionPane.INFORMATION_MESSAGE);
y++;
}
}
catch (Exception e){
JOptionPane.showMessageDialog(frame, "I Didn't Understand That.","...",JOptionPane.ERROR_MESSAGE);
y++;
}
System.out.println ("x: " +x);
System.out.println ("i: " +i);
percentage = (x - y) / i * 100;
System.out.println ("% :" + percentage);
}
}
Say I keep getting perfect, Then percentage = 100.0 when displayed on the interactions pane. HOWEVER when I get one question wrong, instead of getting a percentage number, i automatically get a zero (ex say I got 2 out of 3, percentage = 0 instead of percentage = 66.6. I tried getting rid of the 0 when declaring it, but it only gives me "variable may not have been initialized".

cast one of the integer operands inside the bracket to double to make use of floating point arithmetic .
double percentage = ((double)x - y) / i * 100;
All operands (x,y,i and literal 100) are integers, therefore integer arithmetic division is used which will remove everything after the decimal point.

The problem with dividing ints is Java truncates the decimal portion. You can either make x and y floating point variables or just cast them to float for doing the division and cast them back to get an int as the final result.

Welcome to integer arithmetic.
Try percentage = ((double)x - y) / i * 100;
From the Chapter 15 :
The type of a multiplicative expression is the promoted type of its
operands.
If the promoted type is int or long, then integer arithmetic
is performed. If the promoted type is float or double, then
floating-point arithmetic is performed.

Related

I'm stuck with this calculator program, I'm not getting the right answer [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
My programming course wants me to have this kind of endcome:
Enter the first number!
9
Enter the Second number!
5
9 + 5 = 14
9 - 5 = 4
9 * 5 = 45
9 / 5 = 1.8 and this is the problem, the program I've written only gives me 1.0 as an answer. How can I get this number to be 1.8 not 1.0?
public class Nelilaskin {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number!");
int first = Integer.valueOf(reader.nextLine());
System.out.println("Enter the second number!");
int second = Integer.valueOf(reader.nextLine());
int plus = (first + second);
int minus = (first - second);
int multi = (first * second);
double division = (first / second * 1.0);
System.out.println(first + " + " + second + " = " + plus);
System.out.println(first + " - " + second + " = " + minus);
System.out.println(first + " * " + second + " = " + multi);
System.out.println(first + " / " + second + " = " + division);
}
}
Consider replacing the data type for first and second as Float.
And store the resultant in a float variable as well, then the output would be as required.
float plus = (first + second);
float minus = (first - second);
float multi = (first * second);
float division = first / second;
this is because you are dividing two int values, try to cast at least one of them to double..
double division = (double)first / (double)second ;

Java: How do I set a maximum length for a Double?

How do I set a maximum length for a double?
double divSum = number1 / number2;
String divDisplay = number1 + " / " + number2 + " = " + divSum + " ";
JLabel divSumLabel= new JLabel();
divSumLabel.setText(divDisplay)
How do I set the maximum lenght for divSum?
1 / 3 = 0.333333... How do I set the maximum lenght, so its only 0.333?
I could do:
int maxLenght = 3;
String stringDivSum = String.valueOf(divSum);
String shortDivSum = null;
if(stringDivSum.length() > maxLenght){
shortDivSum = stringDivSum.substring(0, maxLenght);
}
String divDisplay = number1 + " / " + number2 + " = " + shortDivSum + " ";
But when I then do 1 / 3 it prints out 1 / 3 = 0.3?
Use String.format(...)
String.format()
double divSum = Double.parseDouble(String.format("%.3f",(double)number1 / number2)) ;
Precision, double.
We can specify the precision of a double or float. We use the "f" to
indicate a floating-point. Before this we specify ".3" to mean "three
numbers after the decimal."
double dblValue2 = Math.round( .333333 * 1000.0 ) / 1000.0;
this will help you
String.format("%.2f", (double)value);
You can try
System.out.format("%.2f + %.2f = %.2f",number1,number2,divsum)
You basically tell the formatter to expect 3 floats with 2 decimals with %.2f. It is important to supply the variables in order you want them to, so writing ,number1,number2,divsum will yield different results than writing ,number2,number1,divsum If you want to print int, short or long, you use %d. If you want to print string you use %s. But you can also google that.
Also, storing numeric data in String in case of mathematical operations is kind of pointless exercise and only bloats your code.
If you want to store the result of the division with a scale of 3 (i.e. 3 digits after the decimal point), you need to use a BigDecimal for this. This class allows to do arbitrary-precision calculus on decimal values.
int number1 = 1, number2 = 3;
BigDecimal divSum = BigDecimal.valueOf(number1).divide(BigDecimal.valueOf(number2), 3, RoundingMode.DOWN);
The divide(divisor, scale, roundingMode) function of BigDecimal can take a scale (here set to 3) and a rounding mode (here set to DOWN, this rounding mode truncates after the scale has been reached, which is what we want here). This will perform the division and the result will be rounded down with a scale of 3.
You can then print the result with:
String divDisplay = number1 + " / " + number2 + " = " + divSum + " ";
System.out.println(divDisplay); // prints "1 / 3 = 0.333"

Why isn't java doing math correctly [duplicate]

This question already has an answer here:
Java Division error
(1 answer)
Closed 7 years ago.
I was trying to create a probability calculator for fun, but for some reason, java gets the incorrect answer when I divide two numbers. Here is my code....
import javax.swing.JOptionPane;
public class ProbabilityCalculator {
public static void main(String args[]) {
String a = JOptionPane.showInputDialog("One out of.....");
int x = Integer.parseInt(a);
int numLoops = 1000;
int y = 0;
int n = 0;
for (int i = 0; i < numLoops; i++) {
int result = (int) (Math.random() * x + 1);
int result2 = (int) (Math.random() * x + 1);
if (result == result2)
y++;
else
n++;
}
System.out.println(y);
System.out.println(numLoops);
System.out.println(y/numLoops);
double d = (y/numLoops) * 100; //get it? double d??
JOptionPane.showMessageDialog(null, "Out of " + numLoops + " trials, "
+ y + " times it worked, while " + n + " times it didn't.");
JOptionPane.showMessageDialog(null, "Your percentage was " + d
+ "%.");
System.exit(0);
}
}
When I ran this code one time, y was 514, numLoops was 1000, but d would be 0, when d is supposed to be 51.4 (514 / 1000 * 100). Why is this happening?
y/numLoops will be an integer since both arguments are ints. Try (double)y/numLoops or y/(double)numLoops instead.
If you decompose double d = (y/numLoops) * 100; you'll get something similar to those steps:
int r = y/numLoops; - according to the spec an operation having two integer operands will have an int result.
double d = r * 100 here r will be 0 due to being int.

Equations in Java - output is either 0 or incorrect value [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 8 years ago.
I am new to Java and am trying to make a program run to solve and display
the output of the equations. I have tried changing the places of the
parenthesis, and putting equations in other parts of the code but I either get 0
as the output or wrong answers. Any words of wisdom would be greatly
appreciated.
import java.util.*;
import static java.lang.Math.*;
public class JFirstTest
{
public static void main(String[] args)
{
// Declare variables and equations
int W, X, Y, Z;
W = 10;
X = 20;
Y = 30;
Z = 40;
int FormulaOne = (W + X) / (Y + Z);
int FormulaTwo = (X + ( Y / W)) / Z;
int FormulaThree = X * (W - Y)/ (X * Y - Z);
// System.out.println formulas
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaOne = " + FormulaOne);
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaTwo = " + FormulaTwo);
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaThree = " + FormulaThree);
System.out.println("\n");
Update: This has been marked as Duplicate, however, I did searches before I
posted this question and the answers eluded me...Also changed int to double
and now it works fine.
Dividing integer by integer will result in integer, and round down (truncate). So, dividing smaller number by larger will result in zero, so you may want to consider changing type of variables to float / double.
Think of it this way... if an int (integer) is a whole number, then if you divide, for example, 10 by 20, then your program is just going to give you back 0 because 0.5 is not an integer (so it rounds down).
What primitive data type would you use to account for any decimals?
Answer: Double

Rounding int to 1 decimal place?

So in the following set of code I don't understand why "%.1f" will not round y to 1 decimal, I get the following when running the program:
123 F = Exception in thread "main"
java.util.IllegalFormatConversionException: f != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2761)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2708)
at java.util.Formatter.format(Formatter.java:2488)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Check03A.main(Check03A.java:17)
I also tried Math.round(y * 10) / 10 but it gives me for example 29.0 instead of 28.9
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Check03A
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream print = new PrintStream(System.out);
print.println("Enter the temperature in Fahrenheit");
int x = scan.nextInt();
int y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y + " C");
}
}
The problem is here:
print.printf(x + " F = " + "%.1f", y + " C");
There are two arguments to this method:
x + " F = " + "%.1f" (the format string),
y + "C" (the argument)
Condensing the first argument, the statement becomes:
print.printf(x + "F = %.1f", y + "C");
The problem: y + "C". Why? Well, one argument of the + operator is a String; therefore, this + becomes a string concatenation operator and what the argument will ultimately be is String.valueOf(y) + "C".
But the format specification in the format string is%.1f, which expects a float or double, or their boxed equivalents. It does not know how to handle a String argument.
Hence the error.
There is also the problem that you are doing an integer division, but this is not the topic of this question. Provided that all numeric problems are solved, your printing statement will ultimately be:
print.printf("%.1f F = %.1f C", x, y);
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream print = new PrintStream(System.out);
print.println("Enter the temperature in Fahrenheit");
int x = scan.nextInt();
//change it
float y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y).print(" C");
}
Make y as float if you want to use %f
float y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y ).print("C");

Categories

Resources