can anybody explain this why its happening
int i=0;
i=i++;
i=i++;
i=i++;
System.out.println(i);
it prints zero.
i++ is a postincrement (JLS 15.14.2). It increments i, but the result of the expression is the value of i before the increment. Assigning this value back to i in effect keeps the value of i unchanged.
Break it down like this:
int i = 0;
int j = i++;
It's easy to see why j == 0 in this case. Now, instead of j, we substitute the left hand side with i. The right hand side value is still 0, and that's why you get i == 0 in your snippet.
You meant to do this:
int i = 0;
i++;
i++;
i++;
System.out.println(i);
i++ actually does an assignment so if you add an = you just confuse things. These other fine responders can give you the nitty gritty, some details of it escape me. :)
First thing is you should not write this kind of code....
But if we consider for the questions sake then this simple: It has to do with the way the postfix operator "returns" the value. A postfix has precedence over the assignment operator, but the postfix operator after incrementing the value of i returns previous value of i. So i get again assigned to its previous value.
And once again don't use this construct in your code as the next programmer who sees this will come after you (with something big in his hands) :)
Let I=++, an increase, and A=i, an assignment. They are non-commutative: IA != AI.
Summary
IA = "first increase then assignment"
AI="first assignment then increase"
Counter-Example
$ javac Increment.java
$ java Increment
3
$ cat Increment.java
import java.util.*;
import java.io.*;
public class Increment {
public static void main(String[] args) {
int i=0;
i=++i;
i=++i;
i=++i;
System.out.println(i);
}
}
Related
Initialization, assignment and declaration
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 months ago.
import java.util.Scanner;
public class recursion_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
printArray(a, 0);
sc.close();
}
static void printArray(int arr[], int i) {
if (i == arr.length) {
return;
}
printArray(arr, ++i);
System.out.println(arr[i]);
}
}
I am try to print array element using recursion.
But it give error of arrayIndex Out of bound.
Replace ++i with i+1
You are incrementing the value of local variable in function. Instead of incrementing, send next value to other function as you will use that local variable value while printing in your function.
++i increments the value - it actually changes it (and evaluates as the updated value.)
++i, i++ and the subtle distinction between them has been the cause of many and frustrating bugs. This is just my opinion, but I advise never using either one of them except as a single-line statement when you need to increment something. The brevity isn't worth the risk of bugs.
So if you enter printArray with i=arr.length-1, then you get past your i guard, increment i, make the recursive call (which returns), and then try to access `arr[arr.length - 1 + 1], which is out of bounds.
If you're just learning about recursion, you might be confused at how local variables and returns work in a method. Each time you call a method, that's a new stack frame (a section of memory) with completely different values for its local variables, and which returns independently. i is not "i in every usage of the method named printArray", it's only "i in the current application of the method printArray." Similarly when you return, you cease to run the current application of printArray, but not every application.
Sorry if that part's all stuff you know - I find it's one of those things that's completely mind boggling to people starting out, and then becomes completely obvious a week later.
I am trying to learn recursion in Java and have an array that takes in continuous input until the Scanner reads in a 0.
From there I have a method that (attempts) to calculate the number of positive integers in the array using recursion. This is the first recursive function I have ever written and I keep getting a stackoverflow error.
I have read tutorials and I still can't wrap my head around the basic understanding of recursion.
public class reuncF {
private static int start = 0;
private static int end = 98;
public static void main(String[] args) {
input = input.nextDouble();
list[i] = numInput;
computeSumPositive(numList, count);
}
}
return positives += solve(numbers, count++);
}
}
You forgot to stop your recursion!
There has to be some case where computeSumPositive returns without calling itself again. Otherwise it'll just keep going forever, never getting back to you.
If you did it with a loop, the loop would look like this:
int positives = 0;
for (int i = 0; i < numList.length; ++i) {
if (numList[i] > 0) {
positives++;
}
}
To do that recursively, you just find out what are the variables used in the loop. They are i, numList and positives.
computeSumPositive(int i, double[] numList, int positives)
Then we take a look at what the loop does. First, it checks whether we went too far,
so our recursive function should do that too. It'll have to return instead of just falling through like the loop does. And obviously, it must return the result:
{
if (! (i < numList.length))
return positives;
The loop then does the test and maybe increments positives, so the recursive function should also do that:
if (numList[i] > 0) {
positives++;
}
At the end of the loop, i is updated:
i++;
The loop just starts over, but the recursive function will have to call itself. Of course, we want it to use the new value of i and positives, but fortunately we updated those, so now we can just do:
return computeSumPositives (i, numList, positives);
}
The tricky bit is that the values i, numList, and are local to each call. Each invocation of computeSumPositives can see only the arguments it were given. If it changes them, none of the other invocation can see that change.
EDIT: So if we, for reasons we can only speculate about, wanted desperately for computeSumPositive to take only 2 parameters, we would have to "split up" positives across each invocation. Each invocation knows whether or not its number was positive or not; all we have to do is add them. Then it looks like this:
computeSumPositive(int i, double[] numList)
{
if (! (i < numList.length))
return 0; // I didn't find any at index i
if (numList[i] > 0) {
// Theres one I found + however many my later
// invocations will find.
return 1 + computeSumPositive (i+1, numList);
} else {
// I didn't find any, but my later invocations might.
return computeSumPositive (i+1, numList);
}
}
I find it helpful, when dealing with recursion, to figure out the termination case first.
It looks like you are treating 'count' as an index. So you could check if your at the last index in the array, if so and if the value is positive return a 1, if the value is non-positive return a 0 - dont recurse anymore.
If your not at the last index, and the value is positive return a 1 + the recursive function call, or if the value is non-positive just continue to recurse.
This will still cause a stack overflow for large arrays.
The value of count++ is the same as the value of count; the program uses the value and then increments it. But the result is that computeSumPositive keeps calling itself with the same value of count, which leads to infinite recursion. Note that each time computeSumPositive calls another computeSumPositive, each call has its own copy of the parameters (like count) and the local variables; so incrementing one computeSumPositive's copy of count has no effect on the value of count used by other recursive calls.
Change count++ to count + 1, and also add a way to halt the recursion. (At some point, you will be calling computeSumPositive to look at zero integers, and at that point, it should just return 0 and not call itself. You need to think about: how do you test whether you've reached that point?)
I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print.
Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel
Your for loop condition is wrong. You want the condition to be true to continue looping, and false to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for loops.
#rgettman gave the reason your code didn't work above.
The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.
rgettman is completely correct. A for loop should be used as so:
for is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable such as int i = 0; to create a simple integer at 0.
The second parameter will take a condition such as i < 10, to say while the i integer is less than
The third and final parameter will take an incrementing value like, i++, i--, i +=5, or something to that effect.
This part should like like for(int i = 0; i < 10; i++) so far.
Now you need the brackets { and }. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!
I came across the following issue:
private void doStuff(int i) {
if(i>10) {
return;
}
doStuff(i++);
}
public void publicMethod() {
doStuff(i);
}
I would expect this to run doStuff 10 times and then return.
However i++ does not get executed before the doStuff is called again with 0.
Result is an infinite loop. I know how to fix it but I am wondering if this behaviour is correct or a bug.
Now I would expect this to run doStuff 10 times and then return, however i++ does not get execute before the doStuff is called again with 0.
Yes, the result of the post-increment operator is the original value... and then inside the next call to the method you've a new i. So in other words, this call:
doStuff(i++);
is equivalent to:
int original = i;
i = original + 1;
doStuff(original);
From JLS section 15.14.2:
The value of the postfix increment expression is the value of the variable before the new value is stored.
Given that you don't use i again afterwards (and thus any side-effect on it is pointless), why not just simplify your life?
doStuff(i + 1);
(As with all parameters in Java, you're seeing pass-by-value - changing the value of i in the method does not change the value of the caller's argument.)
It behaves as expected it should, you probably want to replace i++ with ++i.
Check the oracle documentation on how to use the prefix/postfix unary increment operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
(excerpt from the linked page)
The ++ operator works just as expected. it first returns the value of the variable, and then increases the variable, hence you always pass 0.
This:
doStuff(i++);
is like:
int x = i;
i += 1;
doStuff(x);
i++ means that: "use value of i and then increment it". It will always be zero when passed down. It is a value type, not a reference type. If that would be an object, that would be no problem because it would be handled as reference.
So, I have to make a random number generator to get numbers ranging from 0 to 400. I'm putting these into an array and then sorting them later on. I just am not sure how to go about doing this. I was given something along the lines of;
public int nextInt(400) //gives me errors
{
random.setSeed(12345L);
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
}
I've already called the random class, since the directions indicated that. I just don't know why this is not working. It's giving me errors especially with the first part; class, interface, or enum expected. Could somebody steer me in the right direction please?
Functions in Java (all programming languages) have "variables" in their definition.
You've got:
public int nextInt(400)
Over here, you want your 400 to be a value that is passed to the function.
Think of this as math. I'm sure you've dealt with something like f(x) = 2 * x. Here, x is the variable, and you "evaluate" f(x) with a value for x. Similarly, in programming, we'd have something like :
public int nextInt(int x)
As you see, our function defines x to be of type int. This is necessary in a language like Java because you're telling the compiler that this function will only accept integers for x.
Now that you've done that, you can use x as a variable in the body of your function.
Note that whenever you use a variable, it first has to be defined. A line such as:
int variable;
defines variable as an int.
Your program is missing these for random, val, arr, and a. Note here that arr and a are arrays (and somehow I get the feeling that they should not be two separate variables).
You should really brush up on variables definitions, arrays, and functions before attempting this question. Your best resource would be your textbook, because it'll explain everything in an organized, step-by-step manner. You can also try the many tutorials that are available online. If you have specific questions, you can always come back to StackOverflow and I'm sure you'll find help here.
Good luck!
You need to define this function within a class definition
even you have specified :
public int nextInt(400)
in this line function returns int and in your whole body u didn't have any return statement.
and yes as Kshitij Mehata suggested dont use 400 directly as value use variable over there.
this should be your function:
public int[] nextInt(int x) //gives me errors
{
random.setSeed(12345L);
int[] a=new int[arr.size];
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
return a;
}
even there is some issue with arr from where this arr come?