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);
}
}
答案 0 :(得分:1)
您的代码似乎很好..
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);
}
public static void main(String [] args)
{
Person p = new Person("Marcx"); // create an object Person
System.out.println(p.greet("Ankit hacker")); //print the greet message
}
}
将输出:Hi Marcx, my name is Ankit hacker
所以你可能是以错误的方式调用它
修改强>
正如Tom在评论中所做的那样,您可能想要更改name
和yourName
答案 1 :(得分:0)
我能够理解您尝试使用此启动级代码执行的操作。你在这里缺少主要方法。这就是你无法执行它的原因。使用main方法
尝试以下代码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 static void main(String args[])
{
Person p = new Person("A");
System.out.println(p.greet("B"));
}
}
$ javac Person.java
$ java Person
Hi A, my name is B
答案 2 :(得分:0)
试试这个
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 static void main(String[] args) {
Person p1 = new Person("Person1");
System.out.print(p1.greet("Person2"));
}
}
输出是:
Hi Person1, my name is Person2
答案 3 :(得分:0)
我没有看到任何代码问题。只是你应该有主要方法:)