I don't know why my variables are getting these values [duplicate] - java

This question already has answers here:
Java: Prefix/postfix of increment/decrement operators
(11 answers)
Closed 9 years ago.
public int Gauss_Jordan(double[][] matrix, int numOfRows, int numOfCols) {
for (int col_j = 0; col_j<numOfCols; col_j++) {
row_i = nonzeros ++;
System.out.println(row_i+" and "+nonzeros);
}
//return matrix;
return 0;
}
up above in the method called "Gauss_Jordan", you can see a for loop where it iterates until a certain condition is met. (duh.. lol sorry).
so i set row_i = nonzeros++ but here's the thing, when I print out each iteration i get
0 and 1,
1 and 2,
2 and 3
. I would expect the output to be:
1 and 1,
2 and 2,
3 and 3.
How come this is not the case?

You'd need ++nonzeros instead of nonzeros++ to get what you expect.

Thats called post-increment;
When you say row_i = nonzeros ++;
first the row_i will get assigned with the value of nonzeros and the nonzero will get incremented.
try pre-increment
row_i = ++nonzeros;

If pre-increment is not what you wanted. Check the initialization of nonzeros and change it into '1` for it to show up as you want. Your codes are functioning as they should.

Related

I want to transfer the element of an array to another array [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
public class Test {
public static void main(String[] args){
int array1[] = {5,8,11,1,6};
int array2[] = new int[5];
for(int transfer=4; transfer<array1.length; transfer--){
array2=array1;
/*this is line 9*/System.out.print(array2[transfer] + " ");
}
}
}
OUTPUT:
6 1 11 8 5 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Test.main(Test.java:9)
Your program runs as long as transfer is smaller than the length of the first array, and it starts at, which is already smaller, and gets reduced by 1 each turn, so it will naturally try to access array2[-1].
Additionally, you have to use
array2[transfer] = array1[transfer]
instead of your current transferring, as this copies the whole array at once.
transfer starts at 4 and all your code ever does is decrement it (make it smaller, 4 to 3, 3 to 2, etc.). Your loop continues as long as transfer<array1.length is true. Since array1.length is 5, and 4 (and 3, and 2, ...) is less than 5, the loop will continue forever or, in this case, until you try to access the entry at index -1 because transfer has been decremented five times.
You can use Arrays to to copy values in a new array like this :
int array1[] = {5,8,11,1,6};
int array2[] = Arrays.copyOf(array1, array1.length);
for (int i = 0; i< array1.length; i++) System.out.print(array2[i] + " ");

Post-Increment in Recursive Method? [duplicate]

This question already has answers here:
Post-increment and Pre-increment concept?
(14 answers)
Java: Prefix/postfix of increment/decrement operators
(11 answers)
Closed 6 years ago.
I'm trying to learn java oop and i find some problem understanding why the use of post-increment in Recursive Method cause error ? I don't understand .
Main Class :
public class Main {
public static void main(String[] args) {
A a = new A();
a.res(0);
}
}
Code work fine :
public class A {
public void res(int a){
if (a < 5)
res(a+1);
System.out.println(a);
}
}
Output : run:
5
4
3
2
1
0
BUILD SUCCESSFUL (total time: 0 seconds)
But in when i use the ++ operator i got StackOverflowError .
public class A {
public void res(int a){
if (a < 5)
res(a++);
System.out.println(a);
}
}
You are confusing a++ and ++a. As per java documentation - "The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value".
In your case the recursive method is always called with the argument 0
The post-increment operator increments the variable after you use it, so it will only increment the variable after the recursive function is returned.
Your code is doing this:
res(a++) //a = 0
//now a = 1
The recursion will never reach that next line, so the recursive function will always call res(0)
References: https://stackoverflow.com/a/2371162/7238307
Well... what do you expect, exactly? Let's re-write your program slightly. Your program (the one that crashes) can effectively be re-written like so, achieving the same effect (that is, crashing due to a StackOverflowError):
public class A {
public void res(int a){
if (a < 5) {
res(a);
++a;
}
System.out.println(a);
}
}
Your variable a will only increment after the recursive call to res has completed... which is never, because you're always invoking res with the same value.
This is how the recusrive calls are resolved with a+1.
a=0, res(0)
+ 0 < 5, res(1)
++ 1 < 5, res(2)
+++ 2 < 5, res(3)
++++ 3 < 5, res(4)
+++++ 4 < 5, res(5)
++++++ 5 = 5, print 5
+++++ print 4
++++ print 3
+++ print 2
++ print 1
+ print 0
Regarding the problem of your code with a++ is that the increment is performed after the the recursive call is performed. So you basically get:
a=0, res(0)
+ 0 < 5, res(0)
++ 0 < 5, res(0)
+++ ...

What is the difference between (++c) & (c++)? [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
postfix and prefix increment operator in a for loop [duplicate]
(2 answers)
Closed 7 years ago.
What is the difference between (++c) and (c++)?
Lets say
c = 4
I know that for (++c) you would increment increment 4 by 1 so 5, but for (c++)?
Both c++ and ++c increment the variable they are applied to. The result returned by c++ is the value of the variable before incrementing, whereas the result returned by ++c is the value of the variable after the increment is applied.
example:
public class IncrementTest{
public static void main(String[] args){
System.out.println("***Post increment test***");
int n = 10;
System.out.println(n); // output 10
System.out.println(n++); // output 10
System.out.println(n); // output 11
System.out.println("***Pre increment test***");
int m = 10;
System.out.println(m); // output 10
System.out.println(++m); // output 11
System.out.println(m); // output 11
}
}
For more info, read this: http://www.javawithus.com/tutorial/increment-and-decrement-operators
Or google post increment and pre increment in java.

Please explain why this code results in infinite loop [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 7 years ago.
for (int i = 0; i < 10;) {
i=i++;
System.out.println("Hello World" );
}
Basically the value of i remains unchanged, and stays 0, so it is infinite. But Why doesnt it change?
If I changed i=i++ to i++, it works. (not infinite loop).
Because i++ increments i after the expression is evaluated so you are basically saying i = i. If you do i = ++i then it will work because it increments i before the expression is evaluated.
Logically, the assignment is done after evaluation of the right hand side, as for any other Java assigment. However, "The value of the postfix increment expression is the value of the variable before the new value is stored." (JLS, 15.14.2. Postfix Increment Operator ++)
The value of i before the incremented value is stored stays zero, because of the assignment.

Does anyone know how to work this out? [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 7 years ago.
Improve this question
What output is produced by the following program?
The answer says 7 but i have trouble working it out.
public class practice {
public static void main(String[] args){
int i = 5;
int b = g(i);
System.out.println(b+i);
}
public static int f(int i) {
int n = 0;
while (n * n <= i) {n++;}
return n-1;
}
public static int g(int a) {
int b = 0;
int j = f(a);
b = b + j;
return b;
}
}
I assume main is getting called. Here is a list of steps that happen
g gets called with 5 as its parameter.
then in function g, f gets called with g's parameter, which is 5
In function f n is set to zero, a while loop is called and every time n*n is less than or equal to its parameter, which is 5, n is incremented. below outlines the while loop.
0*0 is less than 5, increment n from 0 to 1 and continue.
1*1 is less than 5, increment n from 1 to 2 and continue.
2*2 is less than 5, increment n from 2 to 3 and continue.
3*3 is not less than 5, break out of the loop.
n-1, which is 3-1=2, gets returned back to where it was called, in variable j in function g.
b gets assigned to b+j which is 0+2.
b gets returned back to variable b in function main.
b+i, which is 5+2, which is 7, gets printed as the answer.
Your using a number (5) and basically checking what is the first whole number squared that equals more than than 5. Then you negate 1 from the answer and add 5.
So here is the maths:
1. Find the first whole number squared that is larger than 5
0*0 = 0 //+1
1*1 = 1 //+1
2*2 = 4 //+1
3*3 = 9 //3*3 is the first value over 5; loop breaks
2. Negate 1 from 3 (the first whole number when squared that is larger than
3 - 1 = 2; //using 3, negate 1 (also could have used n--)
3. Using the final value 2 add 5
2 + 5 = 7 //using 2 add 5
Answer is 7.
There is some really unnecessary stuff in this code, such as the two extra methods.

Categories