Solved

atFirst java challenge

Posted on 2014-12-04
4
470 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

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!

Question has a verified solution.

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

Suggested Solutions

A short article about problems I had with the new location API and permissions in Marshmallow
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

739 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