【发布时间】:2015-02-16 07:27:18
【问题描述】:
用户应该按顺序在命令行中输入姓名、姓氏和年龄,并显示在 JoptionPlane 中。然后在年龄增加 1 的参数前面再次显示 Dr.。但是我的公共地球方法有问题,我不断收到错误
"constructor Person in class Person cannot be applied to given types;
public Earthling(String name1, String fn1, int age1){
^
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
预期输出(对话框):
比尔·约翰逊 58 岁。
比尔·约翰逊博士今年 59 岁。
这是我的代码:
import javax.swing.JOptionPane;
public class Inheritance {
/**
* main method which begins the program
*
* @param args is the people and age inputed
*/
public static void main(String[] args){
if (args.length <= 1) {
System.out.println("Please enter a viable argument");
System.exit(1); // ends the program
}
Integer age = Integer.parseInt(args[2]);
// Creates a person object
Earthling familyname1 = new Earthling(args[0],args[1], age);
//put here first so it displays without the Dr.
String firstOutput = familyname1.toString();
//calls the phd and birthday methods
familyname1.phd();
familyname1.birthday();
String secondOutput = familyname1.toString();
JOptionPane.showMessageDialog(null, firstOutput);
JOptionPane.showMessageDialog(null, secondOutput);
}
}
/* Stores the first name and age for a person */
class Person {
protected String name;
protected Integer age;
/**
* The Constructer, used for creating objects and initializing data
*
* @param n1 is the Persons first name
* @param a1 is the Persons age
*
*/
public Person(String n1, int a1){
name = n1;
age = a1;
}
/* adds Dr. to the name */
public void phd() {
name = "Dr. " + name;
}
/* adds 1 to the age */
public void birthday() {
age = age + 1;
}
/**
* displays the data in each objects data field
*
* @return The Persons name, family name and age
*/
public String toString(){
String output = name + " is " + age + " years old.";
return output;
}
}
class Earthling extends Person {
protected String familyName;
//Problem Here!
public Earthling(String name1,String fn1, int age1){
name = name1;
familyName = fn1;
age = age1;
}
public String toString() {
String output = name + familyName + " is " + age + " years old.";
return output;
}
}
【问题讨论】:
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。见:How to create a Minimal, Complete, and Verifiable example.
-
你需要在 Earthling 的构造函数中调用 super(name1, age1) 作为第一件事。
-
哇,这么简单的东西……我想还在学习中,非常感谢!
-
如果它解决了你的问题,请将我的答案标记为正确的:)
标签: java inheritance command-line-arguments