Home > front end >  Appending string to the end of the current line
Appending string to the end of the current line

Time:10-24

I'm working through a practice problem for one of my classes and I'm having a bit of trouble with part of the prompt.

We need to:

  • Write code to go through number -20 - 20 (but skip 5-15 inclusively)
  • If the number is negative, the line should start with an "*"
  • If the number is divisible by 2, add "#" to the end of the current line
  • If the number is divisible by 3, add "!" to the front of the line
  • If the previous line has both "!" and "#", then add "wow" to the end of the current line (Hint: use bool)

With the code I've written so far, I've managed to complete the first two tasks on the list, but I run into trouble starting with the third task. In my code I'm using

if (num%2==0)
{
   Console.WriteLine(num "#");
}

but all it's doing is outputting another number with "#" instead of putting "#" on the current line. How do I make it so "#" is appended to the end of the current line?

Here's my code for reference:

static void Main(string[] args)
    {
        int num = -20;
        while (num <= 20)
        {
            if (num < 5 || num > 15)
            {
                if (num < 0)
                {
                    Console.WriteLine("*"   num);
                }
                if (num%2==0)
                {
                    Console.WriteLine(num "#");
                }    
                else
                {
                    Console.WriteLine(num);
                }
            }
            num  ;
        }
    }

CodePudding user response:

Since we are only working with the first 3 points in this question (try the other 2 yourself), I will only address those.

The main problem with the code is that it will always write the number more than once if more than one rule applies to it. There's 2 ways to tackle this. Also note I cleaned up the code a bit and I'll explain why later since it's secondary.

Fix

Method 1 : Incremental Writing

This method uses incremental writing to apply rules and then write a new line at the end before going to the next iteration.

// More succinct than a while loop for this particular scenario
for (int num = -20; num <=20; num  )
{
    //Skip while avoiding nested if
    if (num >= 5 && num <= 15)
        continue;

    //Since it needs to start with * in this case we prioritize it
    if (num < 0)
        Console.Write("*");

    Console.Write(num);

    // Since this would need to be appended at the end if it's true
    if (num % 2 == 0)
        Console.Write("#");

    Console.Write(Environment.NewLine);
}

Method 2: Store the line then print before next iteration

In this case you would build the line that you want to print and then use one Console.WriteLine statement to write it while avoiding duplication. The writing would need to be done before moving to the next iteration.

You can use string concatenation instead of StringBuilder which would generally be more costly but in this case performance doesn't really matter (string are really small and amount of concatenation is minimal). However this would be a typical use case for a StringBuilder.

Also, since we know we know that we will always print out num when we aren't skipping then we can start off with num. But we could also do it like Method 1 where we add it in the middle. I'll illustrate both ways.

StringBuilder constructor with number

// More succinct than a while loop for this particular scenario
for (int num = -20; num <= 20; num  )
{
    //Skip while avoiding nested if
    if (num >= 5 && num <= 15)
        continue;

    // Create and update your string in a string builder, apply rules thereafter
    // (this constructor usage means we don't need to add the number later)
    var line = new StringBuilder(num.ToString());

    //Since it needs to start with * in this case we prioritize it
    if (num < 0)
        line.Insert(0, "*");

    // No need to add the number, already present

    // Since this would need to be appended at the end if it's true
    if (num % 2 == 0)
        line.Append("#");

    Console.WriteLine(line.ToString());
}

StringBuilder constructor without number

// More succinct than a while loop for this particular scenario
for (int num = -20; num <= 20; num  )
{
    //Skip while avoiding nested if
    if (num >= 5 && num <= 15)
        continue;

    // Create and update your string in a string builder, apply rules thereafter
    // (this constructor usage means we must add the number later)
    var line = new StringBuilder();

    //Since it needs to start with * in this case we prioritize it
    if (num < 0)
        line.Append("*"); // NOTICE: This is now Append instead of Insert since line is empty

    // Since we didn't add the number before
    line.Append(num);

    // Since this would need to be appended at the end if it's true
    if (num % 2 == 0)
        line.Append("#");

    Console.WriteLine(line.ToString());
}

Additional Changes

  • for loop is better suited for this situation since you have an int with a clear start, end and an incrementor supported by the structure.
  • Avoid unnecessary nesting of conditions, common newbie mistake. If you have a condition to skip in certain cases, simply check and skip and otherwise the rest of the code will apply. This could otherwise lead to really annoying duplication and condition checks that are unnecessary (most of the time).

CodePudding user response:

use string.concat but first save the string into variable and reach the end and finally do the concatenation

  •  Tags:  
  • c#
  • Related