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.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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.