• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 236
  • Last Modified:

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
0
gudii9
Asked:
gudii9
  • 8
  • 6
  • 5
  • +2
4 Solutions
 
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).
0
 
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

0
 
krakatoaCommented:
>>Math.min()<<

'luckily' Math is a default lang import - otherwise you'd be stuffed - if you didn't import verbatim. ;)
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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

0
 
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
0
 
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

0
 
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
0
 
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.
0
 
awking00Commented:
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
}
0
 
awking00Commented:
Typo, should have been
public String frontTimes(String str, int n) {
0
 
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
0
 
awking00Commented:
>>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 ":"
0
 
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.
0
 
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
0
 
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.
0
 
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.
0
 
awking00Commented:
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)
}
0
 
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)]);
0
 
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
0
 
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)
                            )
                )
0
 
awking00Commented:
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,
0
 
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
0
 
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
0
 
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
0
 
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.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 8
  • 6
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now