这是怎么写这个<class name =“”> <object name =“”> =新构造函数名称的正确方法?</object> </class>

时间:2014-02-23 13:41:24

标签: java

有人可以帮我解决这段代码最后一部分的编译错误 它说创建构造函数请帮助

public class Officer {

     public static void main(String args[]) {

         Scanner input = new Scanner(System.in);

         System.out.print("Enter the name of the Soldier: ");

         String name = input.nextLine();

         System.out.print("Enter the sex of the Soldier: ");

         String sex = input.nextLine();

         System.out.print("Enter the Age of the Soldier: ");

         String age = input.nextLine();

         Soldier soldier = new Soldier(name, sex, age);
    }
}

package officer; 

public class Soldier { 

    private String soldierName; 
    private int soldierAge; 
    private char soldierSex; 

    public void Soldier( String name, char sex, int age) { 
         soldierName = name; 
         soldierSex = sex; 
         soldierAge = age; 
    } 

    public String getSoldierName() { 
        return soldierName; 
    } 
    public char getSoldierSex() { 
         return soldierSex; 
    } 
    public int getSoldierAge() { 
        return soldierAge; 
    }
} 

3 个答案:

答案 0 :(得分:3)

Soldier需要定义匹配的构造函数

public Soldier (String name, String sex, String age) {
    // do stuff
}

当您拨打new Soldier(name, sex, age)

时,这是执行的方法

答案 1 :(得分:0)

没关系,除了:

  • 性别应该是en enum type
  • age应为整数(或浮点)类型
  • 您应验证用户输入

SEX枚举:

public enum SEX {
    MALE, FEMALE
}

构造函数:

public Soldier (String name, SEX sex, int age) {

}

答案 2 :(得分:0)

您需要以下内容:

public class Soldier {

    public Soldier(String name, String sex, int age) {

    }
}

修改:如果提供了新信息,您应该删除void中的public void Soldier,因为void意味着public void Soldierclass Soldier的方法,而它是应该是构造函数。