Tuesday, January 11, 2011

JAVA BAT : String 1 : Hello Name

In String 1 section of Java Bat there are basic string problems in which you cannot use loops to solve the problem. We should use string functions like str.length(), str.substring(i,j) etc.

Hello Name Problem: Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!".

Examples :
helloName("Bob") → "Hello Bob!"
helloName("Alice") → "Hello Alice!"
helloName("X") → "Hello X!"

So, in this problem a string is passed to a method helloName and that method should return a string that have a 'Hello ' concatenated at front and '!' concatenated at the end. As Shown in Examples above. 

Answer For this Java Bat problem:


                         public String helloName(String name) {
                                           name= "Hello "+name+"!";
                                         
 return name;
                         }
 
 
Above Code can also be written in this way:


                         public String helloName(String name) {

                                         
 return "Hello "+name+"!";

                         }

   

1 comment: