Home > Software engineering >  Return a string with characters that come one after the other using while loop Java
Return a string with characters that come one after the other using while loop Java

Time:04-26

How are you =)

I have task to return string with characters "@" "#" one after another with string length of 5 using While loop.

I have an idea to assign "@" to odd numbers, "#" to even numbers.

Where "@" is 0, "#" is 1, "@" is 2, and so on until the end of the length of the line. Unfortunately, I can't find information how I can do this.

Please check the following code, I hope it will be more clear what I am talking about.

I will be glad for any hint or advice, thank you :)

public String drawLine(int length) {
    int i = 0;
    
        while (i < length) {
        
            //I know that the following code will take only the int length, it's just an idea
            if(length % 2 == 0) {
                i  ;
                System.out.print("@");
            }
            else {
                i  ;
                System.out.print("#");
            }
        }
        
    return new String("");
}

public static void main(String[] args) {
    JustATest helper = new JustATest();

    //The result should be @#@#@
    System.out.println(helper.drawLine(5));
}

CodePudding user response:

First of all we've two address two issues here as some have already pointed out in the comments beneath your questions.

You define in your question that your task is to return the final string instead of printing it directly. For such things you can either use a StringBuiler (see my example below) or simply concatenate in any other way ( e.g. "A" "B" -> "AB")

The second issue is the iteration itself. You use mod 2 to determine if the value you test is even or not. This part is correct. However you're always comparing the desired length length % 2 == 0 instead of the current position i of the character to print. Therefore you'll only ever print @ or # length-times depending on the desired length being even (leading to @) or odd (leading to #).

Below you can find my example on how to properly solve your task. Simply exchange length within the if clause with i and concatenate the result and return it.

 public String drawLine(int length)
{
    int i = 0;

    StringBuilder builder = new StringBuilder();
    while ( i < length )
    {
        //I know that the following code will take only the int length, it's just an idea
        if( i % 2 == 0 )
        {
            i  ;
            builder.append( "@" );
        } else
        {
            i  ;
            builder.append( "#" );
        }
    }
    return builder.toString();
}
  • Related