Quick java clarification needed for student [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am reviewing a piece of code that looks like this:
float x = 9;
float y = 5;
int z = (int)(x / y);
Question:
I am wondering why there is a second int on line 3 when it is already declared that z is an int. Thanks in advance.

The result of the division x / y is a float. Java doesn't allow you to assign to an int variable like this, with a narrowing primitive conversion (here, to an int), because this would potentially lose precision. But Java will allow you to do this with an explicit cast, in which Java assumes you know what you're doing.

You have to declare the result (x/y) to be int, otherwise you are trying to set the value of an int variable with a float, which generates a compiler error. This purposeful declaration is required when reducing the precision or range of a number.

According to compilers we are kiddo's.. therefore he(the compiler) wants us to explicitly mention that what we are doing is on purpose and not a mistake, hence we need to specify explicitly..
These are the two scenarios:
1) With (int):
**Program:**
class fox
{
public static void main(String args[])
{
float x = 9;
float y = 5;
int z = (int)(x / y);
System.out.print(z);
}
}
**Output:**
# 1: hide clone input 8 seconds ago
result: success time: 0.07s memory: 380224 kB returned value: 0
input: no
output:
1
2) Without (int):
**Program:**
class fox
{
public static void main(String args[])
{
float x = 9;
float y = 5;
int z = (x / y);
System.out.print(z);
}
}
**Output:**
Main.java:7: error: possible loss of precision
int z = (x / y);
^
required: int
found: float
1 error
# 1: hide clone 6 seconds ago
result: compilation error
// see the compiler cannot understand that we wish to do it purposefully,,

Related

What causes this code not to compile correctly [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 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;

Java Triangle Class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am new to object and classes. I am creating this test program to get the area of the triangle. I kept getting 0 as the area. I have no idea where did I get it wrong.
public class Project1 {
public static void main(String args[]) {
Triangle triangle1 = new Triangle();
System.out.println("The area of the triangle with base "
+ triangle1.base + "and with width "
+ triangle1.width + " is " + triangle1.getArea());
}
}
class Triangle {
double base = 1.0;
double width = 1.0;
double getArea() {
return 1 / 2 * base * width;
}
}
Change the following
double getArea() {
return 1/2 * base * width;
}
To
double getArea() {
return 0.5 * base * width;
}
Due to integer division 1/2 yields 0.
try to use double numbers at getArea() method something like this:
double getArea() {
return 1.0 / 2.0 * base * width;
}
Explanation
You are computing 1 / 2.
This is integer division which does not support decimal values. It always rounds towards zero, the result is thus
1 / 2 = 0
Because of that the computation gets 0 too.
Solution
You can fix it by dividing decimal values instead of integers:
return 1.0 / 2.0 * base * width;
There is no integer division as soon as one of the operands is a decimal value like a double or float. You indicate double by adding the dot like 2.0.
Alternatively you could use the decimal value 0.5 right from the start:
return 0.5 * base * width;
Note that both versions are equally fast since the compiler will pre-compute such constant computations at compile-time. The bytecode will thus have 0.5 for both versions.
It is very common mistake for Java beginners, and I admit I sometimes still make this mistake. When divide one integer by another integer in Java, the result will be an integer as well. So while you expect 1 / 2 will be 0.5, the result will be 0 (i.e. it is truncated). You could cast the number first to force the division to use float or double like:
1 / (float) 2
1 / (double) 2
Or use the shorthand:
1 / 2f
1 / 2d
where f cast the number before it to float, and d to double.

How to swap two variables using bitwise operators (not XOR, and without temporary var) [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 5 years ago.
Improve this question
How to swap two variables using bitwise operators (not XOR, and without temporary var). I need to swap two variables by two ways, one way is XOR as demonstrated below:
int x = 10;
int y = 22;
x = x ^ y;
y = y ^ x; // y is now 10
x = x ^ y; // x is now 22
XOR, p ^ q, can be expressed using the and (&), or (|), and not/invert (~) bitwise operators as (p & q) | ~(p & q) (see Wikipedia's exclusive or article). Hence, we can now simulate an XOR with the other bitwise operators to do the usual swap.
int x = 1;
int y = 2;
x = (x & y) | ~(x & y);
y = (y & x) | ~(y & x);
x = (x & y) | ~(x & y);
Although note Java will create temporary variables to store the intermediate values in the expression (eg. the results of x & y), so in practice or on real architectures this is slower than just storing a variable in a temporary, but from a theory perspective it may satisfy your question.
Note that #ytoamn's answer is a better solution than mine as the JVM wouldn't need to create extra temporary variables to store intermediate parts of expressions. (And isn't just an XOR workaround)
1 way is using a third variable, the other is using addition and subtraction
a = 10, b = 7
a = a - b ; // a = 3
b = b + a ; // b = 10
a = b - a ; // a = 7

find sin-1 of user input for ladder hight [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm trying to find the sin of a number that the user inputs say for eg 1.5. I've done it on the calculator and it works but the code is not working.
Here is the code:
package msd1;
import java.util.Scanner;
public class Part3
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
double Height = scanner.nextDouble();
double Angle = Height/2;
double asine = Math.asin(Angle);
System.out.println("Arcsine of " + Angle + " = " + asine);
}
}
Your variable names make no sense. A "height" is a length, and dividing a length by 2 doesn't give you an "angle". Furthermore, you don't pass an "angle" to asin, you pass it a number from -1 to +1 and it returns an angle.
In your case, you'd want to want to take the height of the ladder and divide it by its length to give you your sin (between -1 and +1), then take the asin of that value.
Odds are you also want to take the angle returned by asin in radians and convert to degrees.
You might have code like this:
double lengthOfLadder = 2.0;
double height = scanner.nextDouble();
double sine = height / lengthOfLadder;
double angleInRadians = Math.asin(sine);
double angleInDegrees = angleInRadians / Math.PI * 180;

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