string front three times

Hi,

I am working on below challenge


http://codingbat.com/prob/p101475

I wrote as below and passed all test cases



Show output only (no red/green)
prev  |  next  |  chance   |  CodingBat  >  Warmup-2      
Expected      Run            
stringTimes("Hi", 2) → "HiHi"      "HiHi"      OK         
stringTimes("Hi", 3) → "HiHiHi"      "HiHiHi"      OK         
stringTimes("Hi", 1) → "Hi"      "Hi"      OK         
stringTimes("Hi", 0) → ""      ""      OK         
stringTimes("Hi", 5) → "HiHiHiHiHi"      "HiHiHiHiHi"      OK         
stringTimes("Oh Boy!", 2) → "Oh Boy!Oh Boy!"      "Oh Boy!Oh Boy!"      OK         
stringTimes("x", 4) → "xxxx"      "xxxx"      OK         
stringTimes("", 4) → ""      ""      OK         
stringTimes("code", 2) → "codecode"      "codecode"      OK         
stringTimes("code", 3) → "codecodecode"      "codecodecode"      OK         
public String frontTimes(String str, int n) {
  if(str.length()<3){
   String results = "" ;
   for(int i = 0;i<n;i++) {
       results += str ;
   }
   return results;
  }
   String result = "" ;
   for(int i = 0;i<n;i++) {
       result += str.substring(0,3) ;
   }
   return result ;
}

Open in new window


Does my code looks ok. Do i need to make some improvement or fix some issues. Please advise
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

krakatoaCommented:
That's ok.

I would prefer myself an if-else structure however, such as -

public String frontTimes(String str, int n) {
String result = "" ;
 if(str.length()<3){
   
   for(int i = 0;i<n;i++) {
       result += str ;
   }
     }
  else{
      for(int i = 0;i<n;i++) {
       result += str.substring(0,3) ;
   }
   }
       return result ;
  }

Open in new window


and then only declare the one String to use to return results.

It could also be considered an improvement if you were to declare a final int such as :  
final int FRONT = 3;

Open in new window


and to then use that FRONT in place of the two 3s. This makes bugs in longer passages less likely, which will be more important when your code gets longer.

(Also, strictly speaking, you would make everything as watertight as possible by putting the entire routine in a try{} catch(){} finally{} construction, returning the 'result' from within that finally clause).
dpearsonCommented:
Your solution is certainly fine.

I think it could be further improved like this which makes 2 changes.

1st - find the front of the string using the "Math.min()" method to decide how many characters you need.

2nd - use StringBuilder instead of a simple String when building up the result.

public String frontTimes(String str, int n) {
   int len = Math.min(3, str.length()) ;
   String front = str.substring(0,len) ;

   StringBuilder result = new StringBuilder() ;
   for(int i = 0;i<n;i++) {
       result.append(front);
   }
   return result.toString() ;
}

Open in new window

krakatoaCommented:
>>Math.min()<<

'luckily' Math is a default lang import - otherwise you'd be stuffed - if you didn't import verbatim. ;)
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

krakatoaCommented:
You can cut things down further with recursion :

public String frontTimes(String st, int n) {
          String rS="";
        
	if (n >0){
		st=st.substring(0,Math.min(3,st.length()))+frontTimes(st,n-1);
	        rS = st;
	}
	return rS;	  
    }

Open in new window

gudii9Author Commented:
final int FRONT = 3;

I have to give static also  as below to make code to compile

public class Test14 {

	/**
	 * @param args
	 */
	final static int FRONT = 3;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		frontTimes("hello",2);
	}
	
	public static String frontTimes(String str, int n) {
		  if(str.length()<FRONT){
		   String results = "" ;
		   for(int i = 0;i<n;i++) {
		       results += str ;
		   }
		   return results;
		  }
		   String result = "" ;
		   for(int i = 0;i<n;i++) {
		       result += str.substring(0,FRONT) ;
		   }
		   return result ;
		}

}

Open in new window


putting the entire routine in a try{} catch(){} finally{} construction, returning the 'result' from within that finally clause

which routine. How to put it. Please advise
krakatoaCommented:
Yes, well you'd have to make it static in the context you are deploying it in there, since, as you already know from other questions, you are calling the method from a static function - main().

This is illustrative of where a finally{} clause could be used  :

public static String frontTimes(String str, int n) {
String result = "" ;
final int FRONT = 3;
try{
  if(str.length()<FRONT){
   
   for(int i = 0;i<n;i++) {
       result += str ;
   }
   //return results;
  }
  else{
   //String result = "" ;
   for(int i = 0;i<n;i++) {
       result += str.substring(0,FRONT) ;
   }
   }
   }catch(Exception e){}
   finally{
   return result ;
   }
}

Open in new window

gudii9Author Commented:
public class Test14 {

	/**
	 * @param args
	 */
	final static int FRONT = 3;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str3=frontTimes("world",3);
		System.out.println("str3 is-->"+str3);
	}
	
	public static String frontTimes(String str, int n) {
		String result = "" ;
		final int FRONT = 3;
		try{
		  if(str.length()<FRONT){
		   
		   for(int i = 0;i<n;i++) {
		       result += str ;
		   }
		   //return results;
		  }
		  else{
		   //String result = "" ;
		   for(int i = 0;i<n;i++) {
		       result += str.substring(0,FRONT) ;
		   }
		   }
		   }catch(Exception e){}
		   finally{
		   return result ;
		   }
		}
}

Open in new window


i wrote as above got output as below in console
str3 is-->worworwor

Is it ok to put static in front of variable as below
final static int FRONT = 3;

And static in front of method as below
public static String frontTimes(String str, int n) {

Also what is importance of returning result inside the finally loop as below
 finally{
               return result ;
               }


I see one warning near finally loop(should i call loop or block or i can call either of them) as attached. I wonder why i got that warning.
please advise
FinallyWarning.jpg
krakatoaCommented:
As I said you need static as the variable and the method are both in static environments themselves. If you were going into production with the code, you'd probably have an instance of the class, and so they would most likely not be static.

The try{}catch(){} finally{} structure is there to ensure that some value is always returned - finally guarantees that. As to why Eclipse doesn't like it, I can't say, as I do not use Eclipse or any other IDE as this is precisely the sort of reason that puts me off doing so.

Maybe it's not my place to say so, and maybe others will disagree, including you, but in my opinion you should try to do more coding using just Notepad and compiling and running with javac.exe and java.exe, rather than relying solely on Eclipse, because coding 'raw' will bring you closer to the JVM and what you write, and closer to the errors that we all make. At least, I would suggest you stick with Eclipse, but run your code with java.exe as well, so that in situations like this with finally{}, you can see whether the same complaints are encountered by the "horse's mouth", or not.
awking00Information Technology SpecialistCommented:
Since you only have two conditions (i.e. str.length <= 3 or str.length > 3) use of the ternary operator is appropriate.
public String frontTimes(String st, int n) {
      String result = "";
      String front = str.length() <= 3? str : str.substring(0,3);
      for (int i = 1; i<=n; i++) {
      result = result + front;
      }
return result
}
awking00Information Technology SpecialistCommented:
Typo, should have been
public String frontTimes(String str, int n) {
gudii9Author Commented:
    String front = str.length() <= 3? str : str.substring(0,3);
Above ternary looks odd to me.How it work in case of true and false.

I thought ternary should be as below
condition?true_stmt:false_stmt like


str.length() <= 3? str.toUpperCase() : str.substring(0,str.length() - 3)
                                    + str.substring(str.length() - 3,str.length)).toUpperCase();

Open in new window




Since you only have two conditions (i.e. str.length <= 3 or str.length > 3) use of the ternary operator is appropriate.

If I have 1 condition what is appropriate to use.
same way if i have 3 conditions what is appropriate to use.
same way if i have more than 3 conditions what is appropriate to use.
Please advise
awking00Information Technology SpecialistCommented:
>>String front = str.length() <= 3? str : str.substring(0,3);
Above ternary looks odd to me.How it work in case of true and false.

I thought ternary should be as below
condition?true_stmt:false_stmt<<
It really should be stated as
condition ? true_stmt value : false_stmt value
The condition is whether or not the length of the string is less than or equal to 3. If that statement is true, return the value after the "?" if not, return the value after the ":"
ozoCommented:
If I have 1 condition what is appropriate to use.
If there is only one case to deal with, there is nothing to test, and you can just
do whatever is appropriate to the one case.
if i have 3 conditions what is appropriate to use.
same way if i have more than 3 conditions what is appropriate to use.
To distinguish between 3 or more cases would require two or more binary tests,
depending on the relationships between the cases, there may be a natural way to do this.
Or, there may be some operation you can do to make some of the cases equivalent
(for example, the Math.min operator might be used for this)
then the remainder of the code can deal with a reduced number of cases.
Or sometimes a switch statement can be a way of dealing with many different cases.
gudii9Author Commented:
To distinguish between 3 or more cases would require two or more binary tests,
when you say binary test you mean using ternary operator right. Please advise
ozoCommented:
The first operand of a ternary ?: operator is a binary test.
The condition in an if  statement is also a binary test.
The left operand of the && and || operators are also binary tests.
krakatoaCommented:
If I have 1 condition what is appropriate to use.
 same way if i have 3 conditions what is appropriate to use.
 same way if i have more than 3 conditions what is appropriate to use.
 Please advise

You can nest if statements and you can nest ternary statements also. You also have case construct, which does the same thing, but in a different way.
awking00Information Technology SpecialistCommented:
The following demonstrates the use of nested if statements, use of nested ternary statements, and use of the switch statement, assuming 4 conditions. str <=3 return str, between 4 and 6 return str.substring(0,4), between 7 and 10 return str.substring(0,5), else return str.substring(0,6):

Nested ifs -
int len = str.length();
if (len <=3) {str
} else if (len > 3 && len < 7 {str.substring(0,4)
} else if (len > 6 && len < 11 {str.substring(0,5)
} else {str.substring(0,6)

Nested ternary operator -
len < 3? str : len >3 && len < 7? str.substring(0,4) : len > 6 && len < 11? str.substring(0,5) : str.substring(0,6

Switch method - (Note - this method is a little cumbersome when making string comparisons)
switch(len) {
  case 0:
     str;
     break;
  case 1:
     str;
     break;
  case 2:
     str;
     break;
  case 3:
     str;
     break;
  case 4:
     str.substring(0,4);
     break;
  case 5:
     str.substring(0,4);
     break;
  case 6:
     str.substring(0,4);
     break;
  case 7:
     str.substring(0,5);
     break;
  case 8:
     str.substring(0,5);
     break;
  case 9:
     str.substring(0,5);
     break;
  case 10:
     str.substring(0,5);
     break;
  default:
     str.substring(0,6)
}
ozoCommented:
if (len <=3) {str
} else if (len > 3 && len < 7 {str.substring(0,4)
missing some punctuatuon
   if (len <=3) { str;
   } else if (len > 3 && len < 7 ){ str.substring(0,4);
Also missing a return or assignment
the len > 3 && is unnecessary, but is ok if it helps you to understand

Nested ternary operator -
or

int len=str.length();
return len <= 3? str : str.substring( 0,len <= 6? 4: len <= 10? 5:6);

when there are many alternatives, you might even consider a structure like:
 return str.substring(0,new int[]{0,1,2,3,4,4,4,5,5,5,5,6}[Math.min(str.length(),11)]);
gudii9Author Commented:
len < 3? str : len >3 && len < 7? str.substring(0,4) : len > 6 && len < 11? str.substring(0,5) : str.substring(0,6

Open in new window


i have not understood clearly above nested ternary statement.

Do i should focus on ? or ; to break above big line. please advise

what is meaning of

len < 3? str
ozoCommented:
len < 3? str
Does not have a meaning unless it is followed by :
len < 3? str : something else
means str when len is less than 3, and something else otherwise.


One way to break up the line, to show nesting with indentation, might be
  len < 3 ?
               str
      :
                len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           len > 6 && len < 11?
                                   str.substring(0,5)
                              :
                                   str.substring(0,6)
                           
With explicit parentheses:
  len < 3 ?
               str
      :
               ( len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           (len > 6 && len < 11?
                                   str.substring(0,5)
                             :
                                   str.substring(0,6)
                            )
                )
awking00Information Technology SpecialistCommented:
ozo,
I agree with everything you stated. I was just trying to use a little "shorthand" to keep my already lengthy response a little shorter.

qudii9,

len <= 3? str : len >3 && len < 7? str.substring(0,4) : len > 6 && len < 11? str.substring(0,5) : str.substring(0,6)
Note, I missed the equals sign.
>>i have not understood clearly above nested ternary statement.<<

In literal terms -
If the condition where the string length is less than or equal to 3 is true then return the string, where it's false test for the
condition where the string length is greater than 3 and less than 7, and if it's is true then return the first 4 characters of the string, where it's false test for the condition where the string length is greater than 6 and less than 11, and if it's is true then return the first 5 characters of the string, and where that's false (meaning none of the conditions are met), return the first 6 characters of the string,
gudii9Author Commented:
len < 3? str : something else

what is something else


whole
( len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           (len > 6 && len < 11?
                                   str.substring(0,5)
                             :
                                   str.substring(0,6)
                            )

or only till next :
 ( len >3 && len < 7 ?
                           str.substring(0,4)

please advise
gudii9Author Commented:
With explicit parentheses:
  len < 3 ?
               str
      :
               ( len >3 && len < 7 ?
                           str.substring(0,4)
                   :
                           (len > 6 && len < 11?
                                   str.substring(0,5)
                             :
                                   str.substring(0,6)
                            )
                )

I feel one extra braket ) at the end. Please advise on where to put begin ( and then ) in case of explicit scenario
gudii9Author Commented:
len <= 3? str : (len >3 && len < 7)? (str.substring(0,4)) : (len > 6 && len < 11)? str.substring(0,5) : str.substring(0,6)

Above explicit paranthesis are correct or i need to modify?
please advise
ozoCommented:
They work. No need to modify if they clarify what you needed clarified.
I thought it was the nesting you wanted to clarify, whereas these clarify the operands instead.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.