Solved

atFirst java challenge

Posted on 2014-12-04
4
456 Views
Last Modified: 2014-12-05
Hi,

I am working on below challenge

http://codingbat.com/prob/p139076
I wrote my code as below

public String atFirst(String str) {
  if(str.length()>=2){
  return str.substring(0,2);
  }
   if(str.length()==1){
  return str.substring(0)+"@";
  }
  else
  {
  return "@";
  }
  
  
  
  }

Open in new window

I am failing below tests.
Expected	Run		
atFirst("hello") → "he"	"he"	OK	    
atFirst("hi") → "hi"	"hi"	OK	    
atFirst("h") → "h@"	"h@"	OK	    
atFirst("") → "@@"	"@"	X	    
atFirst("kitten") → "ki"	"ki"	OK	    
atFirst("java") → "ja"	"ja"	OK	    
atFirst("j") → "j@"	"j@"	OK	    
other tests
OK	    

Open in new window


How to fix and improve my code. Thanks in advance
0
Comment
Question by:gudii9
  • 2
4 Comments
 
LVL 4

Expert Comment

by:Zsolt Pribusz
ID: 40481832
Insert one more @ in line 10:

return "@@";
0
 
LVL 4

Accepted Solution

by:
Zsolt Pribusz earned 250 total points
ID: 40481913
Or you can do this challenge with only one line:

public String atFirst(String str) {

  return (str+"@@").substring(0,2);
    
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40482827
return (str+"@@").substring(0,2);

wHAT IS MEANING OF ABOVE return statement. i never used this kind of return statement. please advise
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 250 total points
ID: 40482861
Breaking it down:
 String temp1= str+"@@";
 String temp2=temp1.substring(0,2);
 return temp2;
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question