I don't understand why the output is 25, from my wrong understanding obviously, i thought it is 20, because: first loop will be: i = 2; x = 5 and there will be 4 more loops since i <= m , therefor 5 x 4 = 20. I know i'm wrong but can't figure out where.
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
while (i<= m){
x = x + m;
i = i + 1;
}
System.out.println(x);
}
}
Let's try a dry-run for this:
x=0;i=1;m=5
while (1<=5) ? yes, so x=0+5; i=2,
while (2<=5) ? yes, so x=5+5; i=3,
while (3<=5) ? yes, so x=10+5; i=4,
while (4<=5) ? yes, so x=15+5; i=5,
while (5<=5) ? yes, so x=20+5; i=6,
while (6<=5) ? no, so exit from loop
And therefore the result is: x=25
Whenver face this type situation, try debugging and printing. Most of the time you'll find your answqer:
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
System.out.println("Initial : x = " + x + " and i = " + i);
while (i <= m) {
x = x + m;
i = i + 1;
System.out.println("x = " + x + " and i = " + i);
}
System.out.println(x);
}
}
Output:
Initial : x = 0 and i = 1
x = 5 and i = 2
x = 10 and i = 3
x = 15 and i = 4
x = 20 and i = 5
x = 25 and i = 6
25
Related
I have been working through 'Head First Java', and spent an inordinate amount of time on what was seemingly a fairly simple question. And yet, could not for the life of me figure out why the method maybeNew seemingly randomly increments. I spent a good amount of time assuming it was dead code.
Does return 1 also operate as an index increaser in this case?
The code output is 14 1.
The question in the book was to work out what different flow control examples would output given the following code: e.g. having x < 19, and index < 1, for instance. Hence my confusion, given the code:
count = count + m4a[x].maybeNew(x);
Thank you for your patience.
public class Mix4 {
int counter = 0;
public static void main(String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x < 9) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1; // 1;, 2;
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index) { // index = 0;
if (index < 5) {
Mix4 m4 = new Mix4(); // m4 0 - 4; rn = 1;
m4.counter = m4.counter + 1; // 1.
// System.out.println(index);
return 1;
}
return 0;
}
}
If that may help:
public int maybeNew(int index) { // index = 0;
if (index < 5) {
Mix4 m4 = new Mix4(); // m4 0 - 4; rn = 1;
m4.counter = m4.counter + 1; // 1.
// System.out.println(index);
return 1;
}
return 0;
}
The whole new Mix4() is useless here: that's a dead variable because you don't really do anything with m4.
So maybeNew can be written as:
public int maybeNew(int index) { // index = 0;
if (index < 5) {
return 1;
}
return 0;
}
The whole maybeNew method could also be static (independent of any instance of Mix4):
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x < 9) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + Mix4.maybeNew(x);
x = x + 1; // 1;, 2;
}
System.out.println(count + " " + m4a[1].counter);
Since the code only ever use m4a[1], the other index are not used; you can move the new Mix4 and further: simplify the loop:
int count = 0;
Mix4[] m4a = new Mix4[20];
m4a[1] = new Mix4();
m4a[1].counter = m4a[1].counter + 1;
int x = 0;
while (x < 9) {
count = count + 1 + Mix4.maybeNew(x);
x = x + 1; // 1;, 2;
}
System.out.println(count + " " + m4a[1].counter);
And finally, remove the array:
int count = 0;
Mix4 m4a = new Mix4();
m4a.counter = m4a.counter + 1;
int x = 0;
while (x < 9) {
count = count + 1 + Mix4.maybeNew(x);
x = x + 1; // 1;, 2;
}
System.out.println(count + " " + m4a.counter);
The loop can then be read:
add one to count 9 times
add result of maybeNew(x):
maybeNew(0) : 1
maybeNew(1) : 1
maybeNew(2) : 1
maybeNew(3) : 1
maybeNew(4) : 1
maybeNew(5) : 0
maybeNew(6) : 0
maybeNew(7) : 0
maybeNew(8) : 0
add 5 to count
= count = 14.
I have been struggling with the break clause aspect of an exercise in the Java Headfirst book( CH5: p121 for reference). I understand how the below code works when the break clause isn't initiated but when it is, I don't get the results I expected.
Can someone please walk me through this?
I understand that the break clause should be activated when the input value is either x = x + 0 or x = x + 6
Below is the exercise code
class MixFor5 {
public static void main (String [] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 0; //input value
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println((x + " " + y));
}
}
My understanding would be that the inner loop would break if x == 6 and thus everything within the inner loop will discontinue including the additional x = x + 3
For x = x + 0. My expected result was x = 6 | y = 18 (actual result x = 6 | y = 14)
For x = x + 6. My expected result was x = 6 | y = 22 (actual result x = 60 | y = 10)
Thanks
For x = x + 0
outer = 0;
inner = 4;
x=x+0, x!=6;
x=x+3=3;
y=30-2=28;
inner = 3;
x=3;
y=28-2=26;
3 != 6;
x=3+3;
inner = 2;
x==6;
y=24;
break;
y=22;
outer=1;
inner=4;
x==6;
y=20;
break;
y=18;
outer=2;
inner=4;
x==6;
y=16;
break;
y=14;
for x=x+6
outer=0;
inner=4;
x=6;
y=28;
break;
y=26;
outer=1;
inner=4;
x=6+6+3;
y=24;
inner=3;
x=15+6+3;
y=22;
inner=2;
x=33;
y=20;
y=18;
outer=2;
inner=4;
x=42;
y=16;
inner=3;
x=51;
y=14;
inner=2;
x=60;
y=12;
y=10;
hope this would help.
public class R {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
int x = 0;
int y = 0;
int j = 0;
int distance = 0;
while (trials>j) {
j = j + 1;
int i = -1;
double counter = 1.0 * distance;
double sum = (distance + counter);
while (i<=n) {
i = i + 1;
if (i == n) {
distance = ((x*x) + (y*y));
}
if (i<n) {
int random = (int )(Math.random() * 4 + 1);
if (random == 1) x = x + 1;
if (random == 2) y = y + 1;
if (random == 3) x = x - 1;
if (random == 4) y = y - 1;
}
}
}
double average= (sum)/(trials);
System.out.println("mean " + "squared " + "distance " + "= " + average);
}
}
Hey guys I'm wondering how it's possible to compute a value within a loop, and then every single time the loop finishes (and the value in computed) to average them together. I can't wrap my head around the concept and I tried doing it in the code above but I can't quite figure it out.
As you can see there are two while loops, and inside one of them a random value (distance) is computed. So essentially I need to average the distances together, but I can't imagine how it's possible to add the distances that are computed each time together into one number. Let's say the loop goes through one time and outputs a singular distance, how would I go about adding a new distance (for the new loop) together with the old one, and then keep doing that for each trial?
You just have to divide the total distance per trials.
public class R {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
int x = 0;
int y = 0;
int j = 0;
int distance = 0, distance_total = 0;
while (trials>j) {
j = j + 1;
int i = -1;
distance = 0;
while (i<=n) {
i = i + 1;
if (i == n) {
distance += ((x*x) + (y*y));
}
if (i<n) {
int random = (int )(Math.random() * 4 + 1);
if (random == 1) x = x + 1;
if (random == 2) y = y + 1;
if (random == 3) x = x - 1;
if (random == 4) y = y - 1;
}
}
distance_total += distance;
}
System.out.println(distance_total/j);
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I need replace the while loop with a for loop. Make sure it produces the same output, if 6 is given as a parameter: java PowersOfTwo 6.
But my answer cannot run well. Always outputs:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Below is the previous example:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int i = 0; // loop control counter
int v = 1; // current power of two
while (i <= N) {
System.out.println(i + " " + v);
i = i + 1;
v = 2 * v;
}
}
}
Below is my answer:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int v = 1; // current power of two
for (int i = 0; i <= N; i ++) {
System.out.println(i + " " + v);
i = i + 1;
v = 2 * v;
}
}
}
I strongly suggest you to use a tool like this - it helps in the majority of cases similar to yours.
java.lang.ArrayIndexOutOfBoundsException: 0 occurs when trying to iterate an empty array - so check if you pass the params into app properly and didn't forget 6 here:
java PowersOfTwo 6
Also I suppose you should remove the i = i + 1; line.
You added i = i + 1 inside the loop which is not necessary here since its already done by the for loop
You can fix it this way:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int v = 1; // current power of two
for (int i = 0; i <= N; i ++) {
System.out.println(i + " " + v);
//i = i + 1; // you dont need this line
v = 2 * v;
}
}
}
Or this way:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int v = 1; // current power of two
for (int i = 0; i <= N;) { //no need to i++
System.out.println(i + " " + v);
i = i + 1;
v = 2 * v;
}
}
}
You can use , to separate multiple variables (and increment commands). So you could do something like,
for (int i = 0, v = 1; i <= N; i++, v *= 2) {
System.out.println(i + " " + v);
}
Finally, when you run the program, pass the value N.
java -cp . PowersOfTwo 4
Which outputs
0 1
1 2
2 4
3 8
4 16
For the same result you could eliminate v, and bitshift 1 left by i like
for (int i = 0; i <= N; i++) {
System.out.println(i + " " + (1 << i));
}
My Code :
class MixFor5 {
public static void main (String [] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 3;
y = y - 2;
if (x == 6) {
break; // *Useless break;*
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y);
}
}
My output:
54 6
Can someone explain to me. Why when I remove break; my output data don't change at all.
You are never fulfilling the if(x==6)
lets take a look at the first loop:
int x = 0;
//....
x = x + 3; // x = 3;
if( x == 6 ) //false
break;
x = x + 3; // x = 6
now the second loop
x = x + 3 // x = 9
if( x == 6 ) //false x = 9
break;
x = x + 3; //x = 12
so you never are equal to 6 when comparing.