Reputation: 410
I am having trouble interpreting a piece of code within the class. The code is:
class PoolPuzzleOne {
public static void main(String[] args) {
int x = 0;
while (x < 4) {
System.out.print("a");
if (x < 1) {
System.out.print(" ");
}
System.out.print("n");
if (x > 1) {
System.out.print("oyster");
x = x + 2;
}
if (x == 1) {
System.out.print("noys");
}
if (x < 1) {
System.out.print("oise");
}
System.out.println("");
x = x + 1;
}
}
}
Result is:
% java PoolPuzzleOne
a noise
annoys
an oyster
I am confused as to what the x = x + 2;
means after the "oyster" printout. Does this mean that this will text x
in increments of '2' instead of the traditional increment of '1' for the particular test of x > 1
?
Upvotes: 1
Views: 1631
Reputation: 7295
When you use an operation like: x = x + 2;
then you are adding that value to that variable.
In the case that x
is a number (int, double, float, Integer, etc)
then, regardless of how you order it the result will always be the same.
For example:
x = x + 2;
is the same as x = 2 + x;
and the same as x += 2;
.
This is almost the same for strings.
If you have this code:
String text = "test";
text = text + 1;
System.out.println(text);
The output will be "test1"
For this code:
String text = "test";
text = text + "1";
System.out.println(text);
The output will also be "test1"
For this code:
String text = "test";
text += "1";
System.out.println(text);
The output will also be "test1"
But this code:
String text = "test";
text = "1" + test;
System.out.println(text);
Will output "1test"
Also, when you increment a number then instead of x = x + 1;
you can use x++;
or ++x;
and when you decrement a number then instead of x = x - 1;
you can use x--;
or --x;
The difference between x++;
and ++x;
is when the addition will happen. x++
means that the addition will happen after the current operation whereas ++x
means that the addition will happen before the current operation.
To explain what this means: if we have the statement System.out.println(x++);
then x
will be printed first and then will be incremented whereas if we use System.out.println(++x);
the value of x
will change and then it will be printed.
This means that for this code:
int x = 1;
int y = 1;
System.out.println(x++);
System.out.println(x);
System.out.println(y++);
System.out.println(y);
The output will be:
1
2
2
2
The same applies for the --
operation except that instead of adding 1 we subtract 1.
Upvotes: 1
Reputation: 1083
The x = x + 2
is used to terminate your while loop. If you notice your while loop only loops while x < 4
but in the case of printing "oyster" x must be at least greater than one. Nothing else seems to be printed out after oyster so, you add 2 to x to make the loop terminate.
Upvotes: 0