I am trying to print the height of my object round by round. It starts at a height of 100 Feet. The catch is, it can go either up or down depending on how much energy is spent per turn. I am having a hard time trying to account for instances with I would go beyond 100---the initial starting height. The goal is an asterisk will appear next to the height of the gameObject, rounding down the nearest 10 value;
I've tried incrementing I when the opposite condition is met, but it just floods the console. Perhaps my sense of logic is just completely off here.
public void printlocation(Object gameObject)
{
int heightToPrint = (gameObject.GetHeight() - (gameObject.GetHeight() % 10));
for (int i = heightToPrint; i >= 0; i -= 10)
{
if (i == heightToPrint)
{
Console.WriteLine($"{i}m:*");
}
else
{
Console.WriteLine($"{i}m:");
}
}
}
As it stands now it prints asterisks for each iteration of the for loop.
You wrote else if (i >= heightToPrint)
instead of else if (i == heightToPrint)
. Also don't do i += 10;
in the body of the loop. You are already iterating through all values from 100 down to 0. It makes no difference whether the object moved up or downwards. Just print a "*" at the height it is.
But you can do it easier with
public void printlocation(Object gameObject)
{
int heightToPrint = gameObject.GetHeight() % 10;
for (int i = 100; i >= 0; i -= 10)
{
Console.WriteLine($"{i}m:{(i == heightToPrint ? "*" : "")}");
}
}