Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

For Loop not looping

813296Dec 3 2010 — edited Dec 3 2010
Provided my example below:
public String front3(String str) {

 // Do not understand why this is not wanting to loop. -> for (initialization(Where to start the loop); termination(When to stop the loop); increment(How much to increase) )
 // here I am starting my loop at 1 and am wanting to only loop it 3 times increasing each time it goes around by 1.
 
 for( int i = 1; i <=3; i++)
  {
 // Here I am only getting the first three letters of a word.
     if( str.length() <= 3)
     {
       return str;
     }
 // First two letters of a word. 
     if( str.length() <=2 )
     {
       return str;
     }
 }
 
 
 return "Wrong"; <-- just put this here because I need a return.... 
}
This is what I am trying to achieve if my loop is willing to work on me... :(
The results:
Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

front3("Java") → "JavJavJav"
front3("Chocolate") → "ChoChoCho"
front3("abc") → "abcabcabc"

Expected	This Run		
front3("Java") → "JavJavJav"	"Wrong"	X	    <- have no idea why its using the return statement.... if I am getting the first three letters of the word
front3("Chocolate") → "ChoChoCho"	"Wrong"	X	<- have no idea why its using the return statement.... if I am getting the first three letters of the word
front3("abc") → "abcabcabc"	"abc"	X	     <---- not wanting to loop 3 times.
front3("ab") → "ababab"	"ab"	X	    <---- not wanting to loop 3 times.
front3("a") → "aaa"	"a"	X	      <---- not wanting to loop 3 times.
front3("") → ""	""	OK
Edited by: 810293 on Dec 2, 2010 9:52 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 31 2010
Added on Dec 3 2010
33 comments
411 views