Note that there are some explanatory texts on larger screens.

plurals
  1. POJava String New Line Loop
    text
    copied!<p>I wrote a method that loops through a string and adds '/n' to create a line length that was given in the parameters. That description is not the best but it's hard to describe so look at the code below. Thanks in advance!</p> <p>My Code: </p> <pre><code>public static String lineLength(String str, int length){ int totalLength = 0; //total length of the document int lengthConst = 0; //constant value of the length for the loop int nLength = 0; // length of \n = 2 characters String work1, work2; //Strings to work with in the loop. Used as string buffers in substrings if(str != null){ totalLength = str.length(); lengthConst = length; } if(length &lt; 1){ throw new NullPointerException("Length must be &gt;= 1"); } /* Main Loop: check again if length is not zero, check if totalLength is not zero, check if pseudoCursor is not zero, check if length is less than or equal to totalLength */ while((length != 0) &amp;&amp; (totalLength != 0) &amp;&amp; (lengthConst != 0) &amp;&amp; (length &lt;= totalLength)){ work1 = str.substring(0, length); //store string of beginning to line length work2 = str.substring(length + nLength, str.length()); //store string from length to end work1 = work1.concat("\n"); //add new line str = work1.concat(work2); //add work1 and work2 and store in str nLength += 1; //nLength increases by 2 because we are going to add another \n length += length; } return str; } </code></pre> <p>When provided with the string "Daniel" and the new line length of 2 this is the run when printed to the console:</p> <pre><code>run: Da n el BUILD SUCCESSFUL (total time: 4 seconds) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload