I am trying to fix the following Java code,
I cannot figure out why the printout is still 5.
public class simpleMath
{
public static void main(String[] args)
{
int number=5;
half(number);
System.out.println("5 divided by 2 is: " + number);
}
private static double half(int number) {
number = number/2;
return number;
}
}
Because you're not re-assigning the returned value.
int number = 5;
number = half(number);
When you call the function, you're discarding its return value:
half(number);
You probably meant to write:
number = half(number);
Also, in Java, arguments are passed by value. This means that, even though you change number inside the function, the change does not propagate back to the caller.
There are several further problems:
Problem 1: The suggested change will store the result in number, which is an integer variable. Thus, the result of half() -- which is of type double -- will be truncated to an integer. To avoid the loss of precision, you either have to change number to be a floating-point variable, or store the result in a different variable of the appropriate type.
Problem 2: The following uses integer division:
number = number/2;
The result is truncated to an integer, i.e. 5 / 2 is 2. The latter is then converted to a double (2.0), which is what the function returns.
To fix, change the function like so:
private static double half(int number) {
return number / 2.0;
}
P.S. Floating-point numbers have a lot of properties that can be unintuitive. I recommend having a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
You passing the primitive data type which is done by value. You need to give SOP in method half()
EDIT: Need to use the result returned by method half() by either assigning it to number or calling this method in SOP itself.
Why half(number) doesn't modify number declared in main() function? It is because you will pass the value of number to half() function to evaluate, i.e. you give a copy of value in number to half() function. Therefore, whatever half() function does to number will not get reflected back to number variable declared in main(). You need to assign the return value of half() to number in main() if you want to update its value.
There are other cases, such as variable shadowing, that I'm not going to talk in details, since it may confuses you.
It's because you're not assigning the return value of half() to number - it gets calculated but not used.
You need to say:
number = half(number);
The way you have it currently would only work if number was being passed by reference, not by value.
int number =5;
half(number);
Java doesn't support pass by reference. So In this case we are passing value that is 5 not reference of number.
So if we want to capture the changes then method call should be like this -
public class simpleMath
{
public static void main(String[] args)
{
int number =5;
number = half(number);
System.out.println(" 5 divided by 2 is:"+ number);
}
private static double half(int number) {
number = number/2;
return number;
}
}
First you need to be aware of what types you are assigning to your variables. You should change your code to look like this:
public class simpleMath
{
public static void main(String[] args)
{
double number = 5;
double answer = half(number);
System.out.println(" 5 divided by 2 is:"+ answer);
}
private static double half(double number) {
number = number/2.0;
return number;
}
}
See how I now use the returned value and how I divide by 2.0? these changes will give you the results you are looking for.
Related
Tried for random numbers by using for loop with count.
I have a field box in that every time it should take random numbers
example: first I enter 1.8$ and run it will accept this number.
after I close the browser and re-run the program it should take the value by its own number but not the previous number mainly it should take decimal values which is greater than 1 & ex: 1.1,1.23 like these numbers only it accepts.
use this method :
public float getDecimalRandomNumber(){
// create instance of Random class
Random rand = new Random();
// Generate and return Random number with decimal
return rand.nextFloat();
}
call it in sendKeys function
driver.findelement(by.id("text box").sendkeys(""+getDecimalRandomNumber());
As you mentioned that the value should not be the previous one, in that case, you should not use any random number. There are chances you will get the same random number. So instead of doing that, you should have to store the state of your variable in a static variable so all the object instances can access the variable and each time increase that number by .1 or by any suitable number. You will not be worrying about the duplication of value.
public class Sample{
private static float inputNumber= 1.1f;
public static float getInputNumber() {
return inputNumber+ 0.1f;
}
}
firstly, im sorry if this is a trivial question. I am a beginner and have been stuck on this for hours.
Below I have tried to create a unitizer method which has a series of if else statements. They are written in descending order, each time checking if a value can be divided by a given number, and if so, performing a division, rounding the value and adding an appropriate unit to the result.
in this question I have attempted to remove all unnecessary code, thus what i am presenting here is only a fragment of the unitizer method.
why is the unitizer method outputting values in hours, when the value should be in seconds?
For clarification, the expected value is ~ 4 seconds.
public class simplified
{
public static void main(String[] args)
{
int i = 5;
double n = Math.pow(2, (double) i);
System.out.println(a6(n)); // correctly displays the expected value.
System.out.println(unitizer(a6(n)));
}
public static double a6 (double n)
{
return Math.pow(2, n); // this value is in nanoseconds.
}
public static String unitizer (double x)
{
String time = "";
if (x/(60*60*1000*1000*1000) >= 1)
{
x = Math.round(x/(60*60*1000*1000*1000) * 100.0) / 100.0;
time = x + "hr ";
}
return time;
}
}
console output:
4.294967296E9
5.25hr
There is an int overflow at the expression 60*60*1000*1000*1000. This means, that the actual result 3,600,000,000,000 is too large to be stored as an int value and is therefore 'reduced' (mod 2^31) to 817,405,952.
This can be fixed by evaluating said expression in a 'larger' arithmetic, e.g. long. There is a nice little modifier, that will force exactly that:
60L*60*1000*1000*1000
^
In particular, it hints the compiler to interpret the preceding literal 60 as a long value and in consequence the whole calculation will be done in long arithmetic.
This modifier is by the way case-insensitive; however I prefer an upper-case L, because the lower-case letter l can easily be mistaken by the number 1.
With this change, the code will not enter the if-statement, because the value x is not larger than one hour. Most probably the omitted code of unitizer will deal with this case.
On a last side note, java has an in-built TimeUnit enum, which can do these conversions, too. However, it does so in long arithmetic and not in double arithmetic as it is required for this specific question.
5! = 5*4*3*2*1.
I have no problem with this. But I noticed with my program that if I type in say 3.5! it would return a defined number.
How do you calculate them?
I have something like this in my program
public class fact {
public static void main(String args[]) {
double factorial=1;
System.out.println("Type a number");
double number= sc.nextDouble(); /*I am using scanner*/
while (number !=0 ){
factorial = factorial * number;
number--;
}
System.out.println(factorial);
}
}
Factorial in its normal definition is defined only for positive integers. If you want to calculate factorials for any real numbers, have a look at Gamma functions.
https://en.wikipedia.org/wiki/Gamma_function
Thing is: factorial is pretty simple for whole, positive numbers.
The concept can also be applied for floating point numbers, but the math behind that could be considered advanced.
So: step back; and understand the math behind the concept; before implementing the concept!
In other words; you have to decide whether you intend to change your program to work with int numbers (validated to be > 0 ); or if you intend to allow floating point numbers. If the later is your goal; then your simple implementation won't do any more.
Beyond that: you want to study the concept of floating point numbers in the first place. It is a misconception to assume that a loop like
double number = ...
while (number !=0 ) {
..
number--;
}
would always stop when using floating point numbers instead of int/long! To the contrary ...
You are getting the defined value even for 3.5!, because your code will calculate it as following:
1*3.5*2.5*1.5*0.5
But actually it is wrong value for 3.5!. The correct value is: 11.6317283966. Your method is only valid for integer inputs. See this for more information about decimal factorials:
this link
I have a config file which includes some factors I want to use for calculations.
public class Config {
public static final double factor = 67/300; // ~0,2233...
}
Im accessing the factors like this:
public class Calculate {
public static calc() {
...
result *= Config.factor;
...
When I do that Config.factor equals 0, so my result is 0, too. I don't have that problem if I set the factor to 0.2233, but that wouldn't be as accurate. Why doesn't setting it to 67/300 work?
Try this:
public static final double factor = 67/300d;
The problem is that 67 and 300 are integer literals, so the division ends up being an integer, which is 0. The d at the end of the number makes it a double literal, so the result of 67/300d is a double.
Note that in the previous code the double literal is 300d. You can also use 67d/300 or 67d/300d.
It should be something like below:
public static final double factor = 67d/300d;
If you don't append 'd' it will be treated as integer that is why you are getting ZERO.
int will be deafault choice. As per doc
For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else
When you enter 67/300, the compiler treats these as int rather than double. Therefore, when the division occurs, the result is floored to 0.
To avoid this, cast the numbers to double either by adding a d after each number (as described in the other answers) or a full type cast with (double).
I am trying to create a recursive method that uses Horner's algorithm to convert a fractional number in base n to base 10. I've searched here and all over but couldn't find anywhere that dealt with the fractional part in detail. As a heads up, I'm pretty weak in recursion as I have not formally learned it in my programming classes yet, but have been assigned it by another class.
I was able to make a method that handles the integer part of the number, just not the fractional part.
I feel like the method I've written is fairly close as it gets me to double the answer for my test figures (maybe because I'm testing base 2).
The first param passed is an int array filled with the coefficients. I'm not too concerned with the order of the coefficients as I'm making all the coefficients the same to test it out.
The second param is the base. The third param is initialized to the number of coefficients minus 1 which I also used for the integer part method. I tried using the number of coefficients, but that steps out of the array.
I tried dividing by the base one more time as that would give me the right answer, but it doesn't work if I do so in the base case return statement or at the end of the final return statement.
So, when I try to convert 0.1111 base 2 to base 10, my method returns 1.875 (double the correct answer of 0.9375).
Any hints would be appreciated!
//TL;DR
coef[0] = 1; coef[1] = 1; coef[2] = 1; coef[3] = 1;
base = 2; it = 3;
//results in 1.875 instead of the correct 0.9375
public static double fracHorner(int[] coef, int base, int it) {
if (it == 0) {
return coef[it];
}
return ((float)1/base * fracHorner(coef, base, it-1)) + coef[it];
}
Observe that fracHorner always returns a value at least equal to coef[it] because it either returns coef[it] or something positive added to coef[it]. Since coef[it] >= 1 in your tests, it will always return a number greater than or equal to one.
It's relatively easy to fix: divide both coef[it] by base:
public static double fracHorner(int[] coef, int base, int it) {
if (it == 0) {
return ((double)coef[it])/base;
}
return (fracHorner(coef, base, it-1) + coef[it])/base;
}