|
Home
Site Map Useful Tools Graphing Calc Scientific Calculator |
What would be the following method calls
Will the code below cause any run time errors? If so, explain.
public String foo(String str){
String r="";
for( int i = 0 ;i < str.length() ;i ++ )
{
r += str.substring( i , i+ 3 ) ;
}
return r;
}
str.substring( i , i+ 3 ) requires that the loop end at .length() -2
public String foo(String str){
String r="";
for( int i = 0 ;i < str.length()-2 ;i ++ )
{
r += str.substring( i , i + 3 ) ;
}
return r;
}
Look at both of the methods below. Which of them correctly returns a String in reverses order. Ie "abcd"
"dcba" Method I
public String reverse(String str){
String r ="";
for( int i = str.length(); i> 0 ; i--)
{
r += str.substring(i-1,i);
}
return r;
}
Method 2 public String reverse(String str){
String r ="";
for( int i = str.length()-1; i>= 0 ; i--)
{
r += str.substring(i,i+1);
}
return r;
}
Method 1 works perfectly fine.
Method 2 does reverse the letters but it misses the first letter, the loop. For Method 2 towork correctly, the loop should be changed to i >= 0. .
** Extra Credit Level
public String myString(String str)
public String mystery(String str){
String r="";
for( int i = 0 ;i < str.length() -2 ;i += 2 )
{
r += str.substring( i , i+ 3 ) ;
}
return r;
}
abcc1223xxyz
|