public class Person{
public static void main(String[] args){
//Class constructor
Person(String name, String status, int Age){
this.name = name;
this.status = status;
this.Age = Age;
}
//Object creation
Person one = new Person("John", "Single", 18);
Person two = new Person("Kez", "Single", 21);
Person three = new Person("Bob", "Married", 31);
//Print out attributes
System.out.println("Person one Profile: %s/t%s/t%d", +one.name, +one.status, +one.Age);
System.out.println("Person two Profile: %s/t%s/t%d", +two.name, +two.status, +two.Age);
System.out.println("Person three Profile: %s/t%s/t%d", +three.name, +three.status, +three.Age);
}
}
我的代码可能有什么问题? 编译器警告的错误并不能帮助我理解问题。
最佳答案
您的代码有 5 个问题。首先,变量应该以小写字母开头,所以我将 Age
更改为 age
。其次,您的构造函数不应位于 main
方法中。第三,您需要 printf
而不是 println
。您还需要去掉那些 +
符号。 +
是一个运算符,需要 2 个 String
(两侧各一个),而不仅仅是一个 String
。最后,我假设您的意思是 \t
而不是 /t
。我已经改变了这一点,还添加了两个换行符。
更正后的代码为
public class Person {
private String name;
private String status;
private int age;
Person(String name, String status, int age){
this.name = name;
this.status = status;
this.age = age;
}
public static void main(String[] args) {
//Object creation
Person one = new Person("John", "Single", 18);
Person two = new Person("Kez", "Single", 21);
Person three = new Person("Bob", "Married", 31);
//Print out attributes
System.out.printf("Person one Profile: %s\t%s\t%d\n", one.name, one.status, one.age);
System.out.printf("Person two Profile: %s\t%s\t%d\n", two.name, two.status, two.age);
System.out.printf("Person three Profile: %s\t%s\t%d", three.name, three.status, three.age);
}
}
关于java - 如何在Java中使用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29810393/