What causes this code not to compile correctly [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Im building a program to round to two decimal places. The user types in a float that they what rounded and it returns that double rounded to the nearest two decimal places. Theres no errors in the code but after compiling the code returns 0.0. Greatly appreciate the help!
package Exercises;
import java.util.Scanner;
class Rounding {
float precise;
float Precision(float f){
f = precise;
precise = (float) Math.round(f*100)/100;
return precise;
}
}
public class Round {
public static void main(String[] args) {
float originalfloat, roundedfloat;
System.out.println(" Type in float number");
Scanner type = new Scanner(System.in);
originalfloat = type.nextFloat();
Rounding ro = new Rounding();
roundedfloat = ro.Precision(originalfloat);
System.out.println(" Original float number :" + originalfloat);
System.out.println();
System.out.println("Rounded float number " + roundedfloat);
}
}

The problem is in this part:
float Precision(float f){
f = precise;
precise = (float) Math.round(f*100)/100;
return precise;
}
When you instantiate a Rounding object here:
Rounding ro = new Rounding();
you initialize precise to 0, because that's what Java does when you don't explicitly initialize primitive numeric types:
float precise;
One you instantiate Precision with a value, you are replacing it with the contents of precise, which has been initialized to 0:
float Precision(float f){
f = precise; // <-- right here, 'f' becomes zero
precise = (float) Math.round(f*100)/100;
return precise;
}
Since f is now 0, Math.round(f*100)/100 will also be 0, and thus the result of the function is 0.

Just remove this line: f = precise; because you dont use given parameter named f then. You just use default value of precise which is 0.0.
float preciseNumber(float f){
precise = (float) Math.round(f * 100)/100;
return precise;
}

I would change this line
precise = (float) Math.round(f*100)/100;
With this line
precise = (float) Math.floor(f*100)/100;

Related

Can someone help me correct my error Finding x using Java? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Could someone help me figure out what I'm doing wrong?
import java.lang.Math;
public class Exercise {
public static void main(String[]args) {
double a = 65;
double angle = Math.cos(20);
double x= (65/angle);
System.out.println(angle);
}
}
This results in 0.40808206181339196 as output.
But that is not what I expected.
Below is the code.
import java.text.DecimalFormat;
public class Test2
{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("#.###");
double o = 65;
double angle = Math.sin(Math.toRadians(20));
double x = o/angle;
System.out.println(df.format(x));
}
}
Problems in your code:
1. Math.cos(20); 20 degree here should be converted to radians because Math class uses Radians not degree as parameters.
2. Formula to find Hypotenuse using angle and opposite side is -> Sine: sin(θ) = Opposite / Hypotenuse
To format decimal number to 3 decimal places I used -> DecimalFormat df = new DecimalFormat("#.###");
math.cos() takes as parameter the angle in radians not degrees. So you have to convert the parameter to get the correct result.
https://www.tutorialspoint.com/java/lang/math_cos.htm

Get a double with only two digits after the dot [duplicate]

This question already has answers here:
Java: How to set Precision for double value? [duplicate]
(11 answers)
Closed 5 years ago.
I’m working on a project at the java and can’t get a very important method to work
I have tried multiple solutions many from similar questions in stackoverflow none of the answers seems to work for may case
What I need is a simple method that will get a double and no matter what is the value of the double as long as there is more than two digits after the dot it will return the same number with only the first two digits after the dot
For example even if the input is “-3456.679985432333”
The output would be “-3456.67” and not “-3456.68” like other solutions gave me
The closest solution that seems to work was
public static double round (double d) {
d = (double) (Math.floor(d * 100)) / (100);
return d;
}
Yet it did failed when the input was “-0.3355555555555551” the output was “-0.34” and not “-0.33” as expected
I have no idea why did it fail and I’m out of solutions with only a few hours left for this project.
Edit: the fix I found was simple and worked great
public static double round (double d){
if (d>0) return (double) (Math.floor(d*100))/100;
else
{
return (double) (Math.ceil(d*100))/100;
}
}
Anyway thanks for everyone that explained to me what was wrong with my method and I will make sure to try all of your solutions
Explanation
Java is working correct. It's rather that floor returns the first integer that is less than (or equal) to the given value. It does not round towards zero.
For your input -0.335... you first multiply by 100 and receive -33.5.... If you now use floor you correctly receive -34 since its a negative number and -34 is the first integer below 33.5....
Solution
If you want to strip (remove) everything after the decimal you need to use ceil for negative numbers. Or use a method which always rounds towards zero, i.e. the int cast:
public static double round (double d) {
d = (double) ((int) (d * 100)) / (100);
return d;
}
(also see round towards zero in java)
Better alternatives
However there are dedicated, better, methods to achieve what you want. Consider using DecimalFormat (documentation):
DecimalFormat formatter = new DecimalFormat("##.##"); //
formatter.setRoundingMode(RoundingMode.DOWN); // Towards zero
String result = formatter.format(input);
Or any other variant, just search for it, there are plenty of questions like this: How to round a number to n decimal places in Java
Something like this would suffice:
public static double truncate(double input) {
DecimalFormat decimalFormat = new DecimalFormat("##.##");
decimalFormat.setRoundingMode(RoundingMode.DOWN);
String formatResult = decimalFormat.format(input);
return Double.parseDouble(formatResult);
}
returns:
-3456.67
and
-0.33
respectively for both examples provided.
you are able to do this, all you need to do is:
number * 10 or (100),
then convert to a int,
then back to double and / 10 (or 100).
10 = for 1 number after digit,
100 = for 2 (if i remember correctly).
public static double CustomRound(double number, int digits)
{
if (digits < 0)
throw new IllegalArgumentException();
long f = (long)Math.pow(10, digits);
number = number * f;
long rnd = Math.round(number);
return (double)(rnd / f);
}
An alternative approach:
public static double round(double number, int digits)
{
if (digits < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(digits, RoundingMode.HALF_UP);
return bd.doubleValue();
}

why i cant take one float and one Boolean variable to convert gallons to letre [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
// convert gallons to leter
class galtolit
{
public static void main(String[] args)
{
double liter;// if this variable is float it throws incompatible type error
// why i can't take float?
double gallons =10;
liter= gallons * 3.7854;
System.out.println(gallons + " gallons = "+ liter+" liter");
}
}
if this variable is float it throws incompatible type error
why i can't take float?
Because you can't take a double value and downgrade it to a float without an explicit conversion, because you'd lose precision in the process. Remember: float is a 32-bit IEEE-754 single precision floating-point value; double is a 64-it IEEE-754 double precision floating-point value. (More in the JLS)
There's no reason to use float here. Stick with the double, which gives you greater precision.
To convert the double to float, you will have to add "f" for type casting. See below:
class galtolit {
public static void main(String[] args) {
float liter;// if this variable is float it throws incompatible type
// error
// why i can't take float?
float gallons = 10;
liter = gallons * 3.7854f;
System.out.println(gallons + " gallons = " + liter + " liter");
}
}

Error when type float, no error when type double

I wrote a simple java program that outputs what your weight would be on the moon. The following code
class MoonWeight
{
public static void main(String args[])
{
double earthWeight = 195.0;
double moonWeight = earthWeight*.17;
System.out.println("On Earth you weigh " + earthWeight +
", on the moon you weigh " + moonWeight);
}
}
Produces the output "On Earth you weigh 195.0, on the moon you weigh 33.150000000000006", but when I use type float:
class MoonWeight
{
public static void main(String args[])
{
float earthWeight = 195.0;
float moonWeight = earthWeight*.17;
System.out.println("On Earth you weigh " + earthWeight +
", on the moon you weigh " + moonWeight);
}
}
I get the following error error: incompatible types: possible lossy conversion from double to float, why is this?
To specify that a number is a float is must end with an F or f so the code would read:
float earthWeight = 195.0f;
float moonWeight = earthWeight * .17f;
this works
float earthWeight = 195.0f;
float moonWeight = earthWeight*0.17f;
see on javadocs: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Data Type Default Value (for fields)
float 0.0f
i.e. every float needs an "f" at the end
0.17 is double, therefore operation with double returns double, in your example this one earthWeight*.17 returns double and you try it to save into float.
To fix it, you have to use float, which is really easy : earthWeight*.17f.
It is similar as if you want to save long into int, you cant do that imlicitly as it cant be done, if that long is too big. Same principle is for double and float.
This is because float is less precise than double. If you convert a number from double to float you can lose information. The compiler tells you about this problem.
It shows you error because decimal literals in java are implicitly double. If you want to use them as a float you have to put letter F/f at the end of your number.
For example: float earthWeight = 195.0F;

Solve an Integral in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to develop a program in Java to solve some integrals. Integrals like this:
I've looked for some functions to do this, in java.Math but I didn't find anything.
Has anyone an idea to get a solution for this? (Maybe some extra libraries or something like that).
The Wikipedia article on Numerical Integration has a section on methods for one-dimensional integrals.
You should have no problem implementing the "trapezoidal" or "rectangle" rule.
The Apache Commons Math library contains, in the Numerical Analysis section, four different numerical integrators:
Romberg's method
Simpson's method
trapezoid method
Legendre-Gauss method
Take a look at JScience
Check out Simpson's Rule on Wikipedia.
/*------------------------------------------------------------------------------------------------------
* Small program that numerically calculates an integral according to
* Simpson's algorithm. Before executing it, you must enter:
* - the expression of the function f: line 12;
* - the lower and upper limits b of the integral: lines 39 and 40;
* - the number of measurements n (n is integer !!!): line 41.
*------------------------------------------------------------------------------------------------------*/
// Class function: Defines Simpson's rule
class Function{
// Define the function to integrate
double f (double x) {
return Math.Cos(x);
}
// Simpson's method for integral calculus
// a = lower bound
// b = upper bound of integration
// n = number of passes (higher = less margin of error, but takes longer)
double IntSimpson(double a, double b,int n){
int i,z;
double h,s;
n=n+n;
s = f(a)*f(b);
h = (b-a)/n;
z = 4;
for(i = 1; i<n; i++){
s = s + z * f(a+i*h);
z = 6 - z;
}
return (s * h)/3;
}
}
class integration{
// Class result: calculates the integral and displays the result.
public static void main(String args[]){
// Call class function
Function function;
function = new Function();
// ENTER the desired values of a, b and n !!!
double a = ???? ;
double b = ???? ;
int n = ???? ;
// Applies simpson method to function
double result = function.IntSimpson(a,b,n);
// Show results
System.out.println("Integral is: " + result);
}
}

Categories

Resources