Forums Register Login

Understanding how this code works..

+Pie Number of slices to send: Send
From my book(HeadFirst Java), I was doing an exercise. This exercise was about putting together few pieces of codes which were already provided and also coming up with the provided output. I did the putting together part(which I think is the easiest part, it compiles and gives the required output as well). But I'm having hard time understanding the logic. Here below is the code and expected output:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
class CodeMagnets
{

public static void main (String[] args){

int z = 3;

if (z >2)
{
System.out.print("a");
}


while (z >0)
{
z = z - 1;
System.out.print("-");



if (z == 1)
{
System.out.print("d");
z = z - 1;

}
if (z == 2)
{
System.out.print("b c");
}





}//end of while
}//end of main
}//end of class

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Expected Output:

C:\>java CodeMagnets
a-b c-d

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Now my questions are mainly regarding those if statements. HOW or WHY making if statement with z, >, = and numeric value could put those letters in such orderly position?

I can READ the code as which line is doing what such as decrementing, initializing variables, if statement and so on. But I'm having hard time with logic. Help please.
+Pie Number of slices to send: Send
The Question you have to ask yourself is: When will the code be used? Under which condition is for example the first if clause used? It should be easy to see then.
+Pie Number of slices to send: Send
Hi Viv,



your first if statment is using the > (greater than operator) and is checking "is current value of z variable greater than 2" z is currently 3 so it is true. Code in if statment will be executed.



The while loop will be executed until the test condition is false. Again, the condition here is using the > operator.

The other operator used in your code is == which is testing is z int value equal to another int value.

I hope these explanations help you look over your code, to understand the logic and what is happening.

Regards,
Jon
+Pie Number of slices to send: Send
Thanks a lot guys. The way I was not right way of thinking. That's why I was having hard time understanding.
I was thinking a-b c-d and 3,2,1,0 as their position in a string. So if my map had to be implemented, the position would have been 0 1 2 3. But the situation here is different abd I realized it. Thanks a lot. I will be back here and talk to you guys again.

Viv
Not so fast naughty spawn! I want you to know about
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 710 times.
Similar Threads
can anyone please explain why these codes work?
Where to find ans for mock test by Valentinn Cretazz
how to encrypt the text
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 05:24:37.