Writing a constructor, takes an enum argument from a different class - java

I am trying to program an AI for a game and I wanna be able to set different modes for players.
Here is my enum in Type.java:
public enum Type {
Human,Random,Minimax
}
And here is the constructor in player.java to set the type of the player:
public Player(String name, Type e ) {
this.name = name;
this.Type = e;
}
Now Eclipse says "Type cannot be resolved or is not a field."
What should I do? Both files are in the same package.

Now Eclipse says "Type cannot be resolved or is not a field."
That's telling you that the problem it has is with the Type in the line:
this.Type = e;
// ^---- This one
Declare a field in Player if you haven't already:
private Type type;
...and then make sure you're using that field's name in the constructor:
this.type = e;
Note I've used lower case for the field name. This is the overwhelming convention in Java, and matches what you did with the field name.

It looks like there is no field Type in your player class.
Something like this would work
class Player {
String name;
Type e;
public Player(String name, Type e) {
this.name = name;
this.e = e;
}
}

Main.java:
public class Main
{
public static void main(String[] args)
{
Player player = new Player( "test", Type.Human );
System.out.println( player.toString() );
}
}
Type.java
public enum Type {
Human, Random, Minimax
}
Player.java
public class Player
{
private String name;
private Type type;
public Player(String name, Type e)
{
this.name = name;
this.type = e;
}
public String toString()
{
return name + " " + type.toString();
}
}
If you compile and run that, toString will return this:
test Human

Related

Can I use the name of the enum constant in the constructor?

Say I have an enum of Things with names:
public enum Thing {
THINGA, THINGB, THINGC, THINGD,
THINGE("Thing E"),
;
public final String name;
private Thing(String pname) {
name = pname;
//...
}
private Thing() {
// See question
}
}
Say I want to do the same thing I did with THINGE for all my other Things, except I want the default name to be the same as that of the enum constant itself, e.g.:
private Thing() {
this(/* the name of the constant itself */);
}
Essentially, I want the implied value of pname to be "THINGA" for THINGA, "THINGB" for THINGB, "THINGC" for THINGC, "THINGD" for THINGD, etc. Using either toString() or name(), the compiler yells:
error: cannot reference this before supertype constructor has been called
Is there any way to avoid this?
Specifically, I include the names for the sake of the user. It feels more natural to look at "Thing E" rather than "THINGE", but its much easier for me to program if I can write a method to turn "THINGA" into "Thing A" and use that in the constructor.
You don't need to give a parameter to the constructor for this, using name() and a bit of String manipulation should get you there.
public static void main(String[] args) {
for (Thing value : Thing.values()) {
System.out.println("value.name = " + value.name);
}
}
public enum Thing {
THINGA,
THINGB,
THINGC,
THINGD,
THINGE;
public final String name;
Thing() {
this.name = name().replace("THING", "Thing ");
}
}
Prints
value.name = Thing A
value.name = Thing B
value.name = Thing C
value.name = Thing D
value.name = Thing E
I believe from your question that you don't want to change what .name() returns, but introduce another field on your enum values which defaults to .name().
You can do this:
public class Comparison
{
public enum Foo {
A, B, C("My C");
private final String myName;
Foo(String myName) {
this.myName = myName;
}
Foo() {
myName = this.name();
}
public String getMyName() {
return myName;
}
}
public static void main(String[] args)
{
System.out.println(Arrays.stream(Foo.values()).map(e -> e.getMyName()).collect(Collectors.joining("\n")));
}
}

I want to make universal method in CLASS for all enums

public class TableContent {
public static String EXCEL_SHEET_NAME = Nit.THEAD.getName();
public static String FILENAME= Nit.FILENAME.getName();
public enum Nit {
FILENAME("Nit-workorder-list"),
THEAD("NIT WORKORDER"),
TENDERSPECNO("TENDER SPECFICATION NO."),
FEE("TENDER FEE"),
SDAMOUNT("SD AMOUNT"),
TYPE("NIT TYPE"),
PRE_BID("PRE BIDDING DATE"),
OPEN_DATE("OPENING DATE"),
STATUS("CONTRACTOR STATUS");
private final String name;
public String getName() {
return name;
}
private Nit(String name) {
this.name = name;
}
public static Nit getNitHeadByName(String name)
{
Nit[] nit=Nit.values();
if(nit==null)
{
return null;
}
for(Nit nitHead:nit)
{
if(nitHead.getName().equals(name))
return nitHead;
}
return null;
}
public enum NitWorkOrder {
}
public enum NitList {
}
My objective is:
I want to export excel sheet from my application, every time I need to hardcode the table headings, which was not good programming practice.
So I use enum to overcome the hardcode problem. Now there are different table heading according to the list, then I enclosed all the required ENUMS in single class.
I used to write getXXXByName() and getXXXByValue() to access the enum, by name or by value.
But he problem is I need to write getXXXByName() and getXXXByValue() everytime inside each enum. I want to write these methods inside the class and outside the enums, and access those methods with the help of class name.
I just want to declare my constants inside enum.
Please kindly suggest me an idea or a way so I can make this method universal which will work for each and every enum. I want to write these methods in such a way so it can be accessed for all enums enclosed in my class. I thought about generics but I have little knowledge.
You can use generics to push functionality up to a parent class by telling the parent class that the type is an enum that implements an interface.
// Use an interface to inform the super class what the enums can do.
public interface Named {
public String getName();
}
// Super class of all Tables.
public static class Table<E extends Enum<E> & Named> {
private final Class<E> itsClass;
private final String sheetName;
private final String fileName;
public Table(Class<E> itsClass) {
this.itsClass = itsClass;
// Walk the enum to get filename and sheet name.
String sheetName = null;
String fileName = null;
for ( E e: itsClass.getEnumConstants() ){
if ( e.name().equals("FILENAME")) {
fileName = e.getName();
}
if ( e.name().equals("THEAD")) {
sheetName = e.getName();
}
}
this.sheetName = sheetName;
this.fileName = fileName;
}
// Use the interface and the enum details to do your stuff.
public E getByName (String name) {
for ( E e: itsClass.getEnumConstants() ){
if ( e.getName().equals(name)) {
return e;
}
}
return null;
}
}
// Extend Table and tell it about your enum using the super constructor.
public static class TableContent extends Table<TableContent.Nit> {
public TableContent() {
super(TableContent.Nit.class);
}
public enum Nit implements Named{
FILENAME("Nit-workorder-list"),
THEAD("NIT WORKORDER"),
TENDERSPECNO("TENDER SPECFICATION NO."),
FEE("TENDER FEE"),
SDAMOUNT("SD AMOUNT"),
TYPE("NIT TYPE"),
PRE_BID("PRE BIDDING DATE"),
OPEN_DATE("OPENING DATE"),
STATUS("CONTRACTOR STATUS");
private final String name;
Nit(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}

Constructor undefined issue

public class Person {
public String Person(String name) {
return name;
}
public static void main(String[] args) {
Person one = new Person("hendry");
}
}
What am I doing wrong?
This is not a constructor, because you have declared a return type. It's just a method that happens to have the same name as your class.
public String Person(String name) {
Without an explicit constructor, the compiler inserts an implicit default constructor with no parameters, so there is a conflict with the number of arguments.
Remove the return type; no return type should be specified on constructors, not even void:
public Person(String name)
Don't return anything from the constructor. But, you may wish to store the parameter in an instance variable, and you may wish to add a method that returns that instance variable (a "getter").
Constructors don't have a return type. Why? Because their purpose of existing is to initialize attributes.
Maybe what you are looking for is a getter method:
public String getPerson(String name) {
return name;
}
But if you want it as constructor, to initialize an attribute, first declare it, and then assign the parameter of the constructor to it:
public class Person {
private String name;
public String Person(String pName) {
this.name = pName;
}
...
}
public String Person(String) is not valid constructor as constructors dont have return type. So actually as per compiler there is no parameterized constructor in your code but you are trying to call one
Constructor returns nothing. They can take parameter but they don't return anything.
It must be like this:
private String name;
public Person(String name) {
this.name = name; }
public String getName(){
return this.name; }
public static void main(String[] args) {
Person one = new Person("hendry");
String name = one.getName();
}

Java Enum Constructor Undefined

Why am i getting an error "Constructor is undefined" is it in my eclipse IDE?
is there something wrong with my code?
public enum EnumHSClass {
PALADIN ("Paladin"),ROUGE("ROUGE");
}
If you expect your enums to have parameters, you need to declare a constructor and fields for those parameters.
public enum EnumHSClass {
PALADIN ("Paladin"),ROUGE("ROUGE");
private final String name;
private EnumHSClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
You need to provide a constructor in your enum like:
public enum EnumHSClass {
PALADIN("Paladin"), ROUGE("ROUGE");
String value;
EnumHSClass(String value) {
this.value = value;
}
}
Note: The constructor for an enum type must be package-private or
private access. It automatically creates the constants that are
defined at the beginning of the enum body. You cannot invoke an enum
constructor yourself.
Ref : http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Enums have constructors too, but only with either private or default visibility:
public enum EnumHSClass {
PALADIN ("Paladin"),ROUGE("ROUGE");
private EnumHSClass(String s) {
// do something with s
}
}
You may want to declare a field and create a getter for it, and set the field in the constructor.
Also note that the name of the enum instance is available for free via the (implicit) name() method that all enums have - maybe you can use that instead.
Your code should look like this:
public enum EnumHSClass {
PALADIN ("Paladin"), ROUGE("ROUGE");
private String name;
private EnumHSClass(String name) {
this.name = name;
}
}
public enum Days {
MONDAY(1), TUESDAY(2);
int val;
Days (int val) {
this.val = val;
}
}

what is the error in this code and why?

class Person {
String name = “No name";
public Person(String nm) { name = nm; }
}
class Employee extends Person {
String emplD = “0000”;
public Employee(String id) { empID = id; }
}
public class EmployeeTest {
public static void main(String[ ] args)
{
Employee e = new Employee(”4321”);
System.out.println(e.empID);
}
}
The constructor of Employee must call its super constructor, the constructor of Person.
public class Person
{
private String name;
public Person(String nm)
{
this.name = nm;
}
public String getName()
{
return this.name;
}
}
public class Employee extends Person
{
private String emplD;
public Employee(String nm, String id)
{
super(nm);
this.empID = id;
}
public String getId()
{
return this.empID;
}
}
public class EmployeeTest
{
public static void main(String[] args)
{
Employee e = new Employee("Some Name", "4321");
System.out.println(e.getID());
}
}
Change “No name’ into “No name" (closing quotes)
Maybe it's here:
String name = “No name’;
should it be:
String name = "No name";
Also, I'm not sure if this is the editor that you've pasted it in from doing this, but this is wrong too:
Employee e = new Employee(”4321”);
should be:
Employee e = new Employee("4321");
A number of things:
You're using the wrong kind of quote characters around your strings. You need to use ". Not “, ', or ”.
Your Person class has no default constructor. Because of this you must explicitly call super("some name"); as the first line of your Employee constructor (I would suggest adding a constructor that takes both name and employeeId as parameters).
You declared the property as emplD (with a lower-case L character), but you try to assign to it as empID (with an uppercase I character). You can call it whatever you want, but the name needs to match in both places.
Your object design violates the basic principles of encapsulation. The name and empID properties should be private fields, and if external classes need access to these values, then you should provide the appropriate public getter methods. In other words, instead of e.empID you should be able to say e.getEmpID().
It is generally not good coding style to define multiple classes in a single file, particularly when all of them are meant to be publicly accessible.
Change this line
String name = “No name’;
to:
String name = “No name";
check your closing qoutes.
Your empID field is not public / there is no accessor method for it / it is not defined as a property. Also don't expect people to help if you provide absolutely no information on the error other than the source code and a vague post title.
You have to call the constructor of the superclass (Person) in the constructor of the class `Employeesuper(id); Please find the correct code below.
public Employee(String id) {super(id);empID =id;
Calling a super class constructor would fix the issue !
public class Person {
String name = "No name";
public Person(String nm) { name = nm; }
}
public class Employee extends Person {
String empID = "0000";
public Employee(String id) {
super("Some Name");
empID = id; }
}
public class EmployeeTest {
public static void main(String[] args){
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}

Categories

Resources