I'm trying to learn Java using my knowledge I have gained from programming in C. In C, I loved the ternary operation. I'm trying to apply this in Java but I'm not sure if I'm doing it correctly. For the following recursive method that sums the from 1 to n, I have the following:
public static void main(String[] args){
int n = 6;
System.out.printf("sum of %d is %d ", n, new learn().sum(n));
}
public int sum(int num){
int result;
result = (num == 1) ? result = 1 : result = num + sum(num - 1);
}
which is giving me an error by stating that + is undefined. If someone could point out where my mistake is at, that would be much appreciated!
Your sum method currently has a return type of void. It therefore cannot return anything. In that case, you cannot be using the method invocation expression as a value, as you do in
num + sum(..)
// or in
System.out.printf("sum of %d is %d ", n, new learn().sum(n));
Change it to
public int sum(int num) {
return (num == 1) ? 1 : num + sum(num - 1);
}
to get the behavior you want.
Assigning result within the ternary expression when you are assigning to it outside of the ternary expression is completely pointless since you can't use the intermediary assignment.
That wouldn't be correct in C, either. The ternary operator evaluates to the selected expression, so don't assign inside it (just assign the result), and you clearly intend your method to return an int. Change the return type and return result (or eliminate the variable entirely and just return the value of the ternary expression).
Change:
result = (num == 1) ? result = 1 : result = num + sum(num - 1);
To:
result = (num == 1) ? 1 : num + sum(num - 1);
What is inside the operators ?: are the possible values of "result".
Related
In the last call on the stack, num will equal 0, so why doesn't the code return 0?
public static int Add(int num) {
return(num == 0 ? 0 : num + Add(num - 1));
}
int num = 7;
I believe your confusion lies in the fact that the last return statement does not directly return 0 to the main(). Instead the return statement will return to the caller of the function. In this case the caller will be itself. Here's a visualization with the extremely simple case of passing 1 to Add():
//num == 1
//Since num != 0, we will return num + Add(num - 1)
//But the compiler doesn't know what Arr(num -1) is
return num + ______;
In the blank space is where the result of Add(num -1) will go. The current call to Add() is pushed onto the stack and a new call to Add(num -1) is called:
public static int Add(int num) {
return(num == 0 ? 0 : num + Add(num - 1));
}
Here num == 0 so the method returns 0. But not to the main. It returns it to the previous call to Add(), right where the theoretical blank is. So:
return num + ______;
Becomes
return num + 0;
Since this is the last call on the stack, this returns to the main, with a result of 1, which is correct for the simply case of calling Add(1)
I am trying to better understand recursion. I am writing a basic geometric series method which I know could be done easier with a loop but that is not the purpose. The method is producing the currect output for the values of 0 and 1 which is simply 1 and 1.5. But for 2 it is outputting 1.25 when it should be 1.75. Any pointers on a better way to approach this?
public static double geometricSum(int n) {
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((int) (1/Math.pow(2, n)));
}
This happens because you are casting a float into a int.
1/(2^2)=1/4=0.25 --> 0
As you are passing your float as an int you're not getting your thing working propperly.
So 0.25 + geometricSum(0)=1.25.
On the first one happens the same. you pass the 0.5, but turned into an int so you.re not getting your aproximation propperly done.
As an advice, ALWAYS put () on your math functions in order to make the program, and you yourself, understand in which order it computes the numbers.
The first problem is the cast to int, giving the wrong result, already described by reyeselda95.
There is a second problem hidden, which is that if you fix that you get this:
public static double geometricSum(double n) {
System.err.println("Calling with " + n);
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((1/Math.pow(2, n)));
}
Calling this with the provided value of 2, leads to a loop between calls with the following values, leading to a stack overflow.
...
Calling with 0.4999999999999999
Calling with 0.5000000000000001
Calling with 0.4999999999999999
Calling with 0.5000000000000001
...
This may be the function you are looking for, if I understand correctly:
public static double geometricSum(int count) {
if (count == 0) {
return 1;
}
return geometricSum(count-1) + Math.pow(2, -count);
}
Don't cast float to int;
When using float, are you sure your formula is correct? The recursion breaks if an argument is zero, but you will get StackOverflowError when passing the result of 1.0/Math.pow(2, n) to the function.
This is my python code:
def geometricSum(k):
if k == 0:
return 1
return 1/2**k + geometricSum(k-1)
k = int(input())
print(geometricSum(k))
This is all about the power of 2 i.e. 2 Pow n where n is an integer.
Here Recursion is used to get the sequence of values for n.
In my case I've to calculate the value for 1/(2 pow n).
This question already has answers here:
How to return multiple objects from a Java method?
(25 answers)
Closed 9 years ago.
after c++ i am trying to learn some java, and i have a question about the code i have been working on. I am working on a Fraction class and i got stuck in reduce section. Since the method did not let me to return both "num" and "den", I had to return "n"
This is my method
public double reduce() {
int n = num;
int d = den;
while (d != 0) {
int t = d;
d = n % d;
n = t;
}
int gcd = n;
num /= gcd; //num = num / greatestCommonDivisor
den /= gcd; //den = den / greatestCommonDivisor
return n;
}
I am trying to do "return num, den;" however it does not let me.
and this is what i get
to reduced test for 100/2 is 2.0
to reduced test for 6/2 is 2.0
when i run
System.out.println("to reduced test for " + f4.toString() + " is " + f4.reduce());
System.out.println("to reduced test for " + f6.toString() + " is " +f6.reduce());
Why do i get the 2 when when i am supposed to get 50/1 and 3/1 ? If the IDE let me return num and den at the same time, would that have fixed it?
Thanks
Java has no native way of doing this, you only can return one Object or primitive. This leaves you two options:
Return an array with length 2.
public int[] reduce()
{
...
return new int[]{num, den};
}
Return an object of a wrapper class containing the two numbers.
public Fraction reduce()
{
...
return new Fraction(num, den);
}
It looks like your reduce method is modifying the object. It's unclear what exactly you want to return. If you want the fraction to return itself, then return this;, with the method returning a Fraction in the declaration.
I need to write a Java program that prompts the user to enter an integer consisting of exactly 2 digits; then displays on the screen the sum of its individual digits.
I am stuck here. What am I doing wrong?
import java.util.Scanner ;
public class ss {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x;
System.out.println("Please Enter a number consists of 2 digits only : ");
x = input.nextInt();
x.length() == 2;
}
}
and the last line contains an error!
Assuming that x is positive, a simple way to check if it has exactly two digits would be:
if (x >= 10 && x <= 99) {
// x contains exactly two digits
}
The variable x is of type int, so you can't call a method on it. You need to either read the input as a String or convert the int to a String then call length(), or just test that the int is between 10 and 99, inclusive.
In a programming langauge, there are things called L-values and R-values. In an assignment operation, a L-value can accept a R-value as input. This comes from the typical layout which has L-values on the left of the assignment operator and R-values on the right side of the assignment operator.
x = 5;
x is the L-value and 5 is the R-value. It is possible to assign five to x.
However, a function returns a R-value. Therefore, it is possible to do this
x = a.length();
but is is not possible to do
a.length() = x;
because you can not assign a value to the return of a function.
Fundamentally, L-values are names which represent a value, but R-values are values or items which when analyzed result in the return of values.
Now, if you used the equals comparison operator, both values must be R-values, because no assignment is being performed
a.length == x
is just fine, because it is not the assignment operator = but rather one of the comparison operators ==.
Your error comes because x is a primitive, not an object. Only objects have methods like length(). A quick an easy way to determine the length of an integer is by using Math.log().
public int length(int n){
if (n == 0) return 1; // because Math.log(0) is undefined
if (n < 0) n = -n; // because Math.log() doesn't work for negative numbers
return (int)(Math.log10(n)) + 1; //+1 because Math.log10 returns one less
//than wanted. Math.log10(10) == 1.
}
This method uses the fact that the base b logarithm of an integer a is related to the length of the integer a.
Or, if you don't know how to use methods, you could do this (assuming n is the integer to check):
int length = (n == 0)? 1: ((n > 0)? (int) (Math.log(n)) + 1: (int) (Math.log(-n)) + 1);
Or, if you don't use the ternary operator, you could expand it:
int length = -1; //placeholder; might not need it.
if (n == 0) length = 1;
else if (n > 0) length = (int) (Math.log(n)) + 1;
else length = (int) (Math.log(-n)) + 1;
You can't find the length of an int by calling a method on it, but you can find the length of a String.
Try converting the int to a String and finding the length of that:
boolean isTwoDigits = x.toString().length() == 2;
You cannot call length on integer just write
if(x>=10 && x<=99)
{
//write your code here
}
Can you clearly explain the difference between the operator += and the operator =+ ?
Obviously, both are shortcuts for a sum, but I don't get the meaning of "=+"
a += b is equivalent to a = a + b. But what is the equivalence of a =+ b ???
Here is the practical example:
public class SumOfSquares {
private int[] inputArray;
private Integer result;
public SumOfSquares(int[] inputArray) {
this.inputArray=inputArray;
result = new Integer(0);
}
public Integer getResult () {
for (int counter=0; counter<inputArray.length; counter++) {
int currentNumber = inputArray[counter];
result += currentNumber*currentNumber;
}
return result;
}
}
inputArray={1,2,3,4,5}. Expected result=55 (1^2+2^2+3^2+4^2+5^2 = 1+4+9+16+25 = 55)
If I replace result += currentNumber*currentNumber; by result =+ currentNumber*currentNumber;, I get a result of 25 instead of 55. I would like to understand why.
=+ is not an operator. You might be confusing it with the combination of the assignment = and the unary + operator, which will take the value as positive (doesn't change its sign, + (-3) is still -3) and can be perfectly ommitted for integer values.
int a = 5;
int b = 3;
a = (+b); // a = 3
a = (-b); // a = -3
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
a=+b is the same as a=0+b, in other words, a=b
=+ is not an operator. it is the assignment operator =, followed by a positive sign +. The + is applied to the variable to the right, so you can read it as a= (+b).
a -= b is equivalent to a = a - b, and
a =- b is equivalent to a = - b
No, both are not shortcuts for a sum. Have you tried =+ to see what it does?
Hint, try with =- to see what that does.