I'm trying to get an account in Codewars and was surprised you have to show them you have some basic knowledge in one of the programming languages offered. I chose Java but got stuck in one the exercises. The code is:
public class Person {
String name;
public Person(String personName) {
name = personName;
}
public String greet(String yourName) {
return String.format("Hi %s, my name is %s", yourName, name);
}
}
It says, "Correct this code, so that the greet function returns the expected value". The thing is, I do not see the error and in fact I copied the code to Eclipse and after changin the Java compiler and use version 1.6 the code works, no error and if you try it with a main method it returns the expected value.
If only they tell you which the expected value is... When submitting, no matter what I try I always get "The code does not work as expected".
Any ideas?
You are correct; this code is correct as written, and the Codewars guys are boneheads. They probably want you to switch the names around the other way.
The OO metaphor for calling a function on an object and passing an argument is "tell the object to perform the action on the given object". In other words, if the object is Jim
, then Jim.greet("Joe")
is telling Jim to greet Joe, and "Hi, Joe, my name is Jim" is the right thing to do.
Actually, since greeting is really a communication between two persons, the real correct thing to do is not to pass a string name to greet
, but to pass a Person
, and have greet
call that Person
's beGreeted()
method.
The Answer Is : Justyou need two swap the variables in String.format().
Question:
return String.format("Hi %s, my name is %s", name, yourName);
Answer :
return String.format("Hi %s, my name is %s", yourName, name);
public class Person
{
String name;
public Person(String personName){
name = personName;
}
public String greet(String yourName)
{
return String.format("Hi %s, my name is %s", yourName,name);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With