我刚刚尝试注册,目前正在进行练习,试图找出它。这是代码。
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", name, yourName);
}
}
这些是我所做的改变,当时似乎有意义,但我仍然会通过它来找到有效的方法
public class Person {
String name;
public Person(String personName)
{
name = "John";
}
public String greet(String "Tommy");
{
return String.format("Hi %s, my name is %s", name, yourName);
}
}
如果我将它粘贴到Eclipse中并从那里运行它是否会作弊?
我希望这很清楚,如果我有任何方法可以改进这篇文章或让任何事情更清楚,请告诉我:)谢谢!
答案 0 :(得分:1)
你只需要在String.format()函数中交换name和yourName,参见下面的代码
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);
}
}
答案 1 :(得分:0)
以下代码中的更正和评论。如果你学习一些语言的基础知识,你将会理解一切,否则它会很有趣。
public class Person {
String name;
//This is a constructor and invoked during creation of object
public Person(String personName)
{
//makes no sense to pass personName to construct but, not use it
//name = "John";
name = personName;
}
//A method signature does not end with semi-colon
//You cannot pass string literal in function as argument, "Tommy" incorrect arg
//public String greet(String "Tommy");
public String greet(String greeting)
{
//not sure where you come up with yourName but, i replaced with greeting arg
return String.format("Hi %s, my name is %s", name, greeting);
}
//add main to show you how this works, when run execution enters main first
public static void main(String[] args) {
//an object of Person class is created passing "John" to its constructor
Person p = new Person("John");
//p.greet() invokes the greet method of Person object
System.out.println(p.greet("Oops!"));
}
}