I have three classes in my program. Ship.java, Cabin.java and Passenger.java. According to the program a single cabin can hold upto a maximum of 3 passengers. I'm trying to set passenger details but i keep getting this error
Cannot invoke "classes.Passenger.setFirstName(String)" because
"classes.Main.myShip[0].passenger[0]" is null at
classes.Main.main(Main.java:22)
Ship.java
public class Ship
{
public static Scanner scanner = new Scanner(System.in);
public static Cabin[] myShip = new Cabin[12];
public static void main(String[] args)
{
for (int count = 0; count < 12; count++)
{
myShip[count] = new Cabin();
}
myShip[0].passenger[0].setFirstName("a");
}
}
Cabin.java
public class Cabin
{
int cabinNumber;
Passenger[] passenger = new Passenger[3];
public Cabin()
{
}
public Cabin(int cabinNumber, Passenger[] passenger)
{
this.cabinNumber = cabinNumber;
this.passenger = passenger;
}
public void setCabinNumber(int cNumber)
{
cabinNumber = cNumber;
}
public int getCabinNumber()
{
return cabinNumber;
}
}
Passenger.java
public class Passenger
{
String firstName;
String lastName;
int expenses;
public Passenger()
{
}
//Constructors
public Passenger(String cabinFirstName, String cabinLastName, int pExpenses)
{
firstName = cabinFirstName;
lastName = cabinLastName;
expenses = pExpenses;
}
public void setFirstName(String cabinFirstName)
{
firstName = cabinFirstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String cabinLastName)
{
lastName = cabinLastName;
}
public String getLastName()
{
return lastName;
}
public void setExpenses(int pExpenses)
{
expenses = pExpenses;
}
public int getExpenses()
{
return expenses;
}
}
Please be kind enough to help me out.
Your model is wrong. A ship can (and does) have cabins with no occupants. You have provided no way to have unoccupied cabins. Your cabins need to be fully booked before the ship can be built!
I would consider redefining your Cabin class to be constructed empty -- which means it would have a constructor with a signature like Cabin(), and then provide a way to assign Passengers to Cabins. Maybe this would be a method in the Cabin class, like
boolean assignPassenger(Passenger p) {
... check occupancy...
... return false if full up ...
... otherwise add 'p' to the passenger array ...
... and return true ...
}
You're halfway there in that you're attempting to set the Cabins in the Ship by using a Cabin() constructor -- which is essentially an empty Cabin -- but you have not actually implemented a constructor with that signature.
What I'm getting at here is that, rather than just tweaking some Java, I think you should rethink it a bit. You'd want, I think, to be able to have unoccupied cabins and to be able to determine which cabins are occupied.
I'm writing a program using two classes. I have to prompt user to add an item as a string, set the priority as low/high/medium, and get the date. All these are ToDoItem objects that are stored in an ArrayList called toDoItems. Depending on the priority that the user has inputted, each ToDoItem object holding the item, priority, and date should sort itself out.
For example:
Add item: Run
Set due date: 11/27/2015
Enter priority: High
Print All items:
0. Run -1- (11/27/1993)
Add item: Jump
Set due date: 11/28/1993
Enter priority: Low
Print All items:
0. Run -1- (11/27/1993)
1. Jump -2- (11/27/1993)
Add item: Walk
Set due date: 11/19/1993
Enter priority: Medium
Print All items:
0. Run -1- (11/27/1993)
1. Walk -2- (11/19/1993)
2. Jump -3- (11/27/1993)
At some point i have to be able to delete a ToDoItem object from the arrayList according to it's index which i wrote:
public static void deleteToDoItem() {
System.out.print("Enter index of item to delete: ");
int delete = k.nextInt();
toDoItems.remove(i);
}
Which gives me an error of
----jGRASP exec: javac -g MyList.java
MyList.java:75: error: class, interface, or enum expected
public static void deleteToDoItem() {
^
MyList.java:83: error: class, interface, or enum expected
int delete = k.nextInt();
^
MyList.java:84: error: class, interface, or enum expected
toDoItems.remove(i);
^
MyList.java:85: error: class, interface, or enum expected
}
^
4 errors
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
I got all the objects down and both my classes are working but i'm stuck on how to write my priority enum. I know at some point i have to:
write an enumerated type that represents priority high, medium, and low.
Change the priority field of this object to use this newly defined enumerated type.
& write a single method that now only accepts the newly defined enumerated type.
UPDATE //Sharing full code
ToDoItem class:
import java.text.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class ToDoItem {
private String description;
private static Date dueDate;
private Priority priority;
private static DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
public ToDoItem() {
}
public ToDoItem(String desc) {
description = desc;
dueDate = null;
priority = priority.HIGH;
}
public ToDoItem(String desccription, String d) throws ParseException{
this.description = description;
dueDate = df.parse(d);
}
public ToDoItem(String description, String p, String d) throws ParseException{
this.description = description;
this.priority = Priority.valueOf(p.toUpperCase());
dueDate = df.parse(d);
}
public String toString() {
return description + " -"+priority+"- " + df.format(dueDate);
}
public static void setDueDate(String s) {
try {
dueDate = df.parse(s);
} catch(Exception ex) {
System.out.println(ex);
}
}
public String getDescription() {
return description;
}
public String getDueDate() {
return df.format(dueDate);
}
}
MyList class:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
import java.text.*;
public class MyList {
public static ArrayList<ToDoItem> toDoItems = new ArrayList<>();
private static Scanner k = new Scanner(System.in);
public static void main(String[] args) throws ParseException {
while(true) {
printMenu();
processInput();
}
}
public static void printMenu() {
System.out.println("[a]dd an item");
System.out.println("[d]elete an item");
System.out.println("[t]oggle complete");
System.out.println("[p]rint all");
System.out.println("[q]uit");
}
private static void processInput() throws ParseException {
Scanner s = new Scanner(System.in);
String input = s.next();
if(input.equals("a")) {
addToDoItem();
}
else if(input.equals("d")) {
deleteToDoItem();
}
else if(input.equals("t")) {
// toggleComplete();
}
else if(input.equals("p")) {
printAll();
}
else if(input.equals("q")) {
System.exit(0);
}
}
private static void addToDoItem() throws ParseException {
System.out.print("Enter an item to add to list: ");
String desc = k.nextLine();
System.out.print("Enter Date (MM/dd/YYYY): ");
String dueDate = k.nextLine();
ToDoItem.setDueDate(dueDate);
System.out.print("Enter priority (Low/Medium/High): ");
String prior = k.nextLine();
//int p = Integer.parseInt(prior);
toDoItems.add(new ToDoItem(desc, prior, dueDate));
}
public static void printAll() {
//System.out.print(toDoItems.size() + ". ");
for (int index = 0; index < toDoItems.size(); index++)
System.out.println(index + ". " + toDoItems.get(index));
}
public static void deleteToDoItem() {
int index = 0;
System.out.print("Enter index of item to delete: ");
int delete = k.nextInt();
toDoItems.remove(index);
}
// public static void toggleComplete() {
/////
// }
}
The compilation error which you are getting, that is because of the improper closing brackets for class. Remove the closing bracket after the printAll method and add it after the deleteToDoItem method. That will solve your compilation issue.
The last part of the code, it should be like this:
private static void printAll() {
for (int index = 0; index < toDoItems.size(); index++)
System.out.println(toDoItems.get(index));
}
// Extra bracket is removed from here.
public static void deleteToDoItem() {
System.out.print("Enter index of item to delete: ");
int delete = k.nextInt();
toDoItems.remove(i);
}
} // put it here.
The variable i is also undefined in the deleteToDoItem method.
You can define the Priority enum. Make use of the getValue() method for fetching the int values of the Priority.
enum Priority {
HIGH(1), LOW(3), MEDIUM(2);
private int value;
Priority (int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
The the ToDoItem class will look like this:
Note: It will expect Priority as String like (high, low or medium) instead of integer. Also now all the members of the class are instance variable not the class variable. They now belong to individual object of the ToDoItem class.
public class ToDoItem {
private String description;
private Date dueDate;
private Priority priority;
private static DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
public ToDoItem() {
}
public ToDoItem(String desc) {
description = desc;
dueDate = null;
priority = Priority.HIGH;
}
public ToDoItem(String desccription, String d) throws ParseException{
this.description = description;
dueDate = df.parse(d);
}
public ToDoItem(String description, String p, String d) throws ParseException{
this.description = description;
this.priority = Priority.valueOf(p.toUpperCase());
dueDate = df.parse(d);
}
public String toString() {
return description + " -"+priority+"- " + df.format(dueDate);
}
public void setDueDate(String s) {
try {
dueDate = df.parse(s);
} catch(Exception ex) {
System.out.println(ex);
}
}
public String getDescription() {
return description;
}
public String getDueDate() {
return df.format(dueDate);
}
}
You can avoid this integer conversion in the MyList class, enter the Priority as (high, low or medium), and pass it directly to the ToDoItem class constructors.
int p = Integer.parseInt(prior); // not required.
To print the data in sorted manner you need to implement a custom Comparator. Here is the code which uses the custom Comparator based on the Priority of the ToDoItem object.
public static void printAll() {
Collections.sort(toDoItems, new Comparator<ToDoItem>() {
#Override
public int compare(ToDoItem o1, ToDoItem o2) {
return o1.getPriority().getValue() - o2.getPriority().getValue();
}
});
//System.out.print(toDoItems.size() + ". ");
for (int index = 0; index < toDoItems.size(); index++)
System.out.println(index + ". " + toDoItems.get(index));
}
Also get the getter into the ToDoItem class for Priority:
public Priority getPriority() {
return priority;
}
I am creating a flight controller application. A bit of functionality that i want is to be able to tell the user what the next flight is according to a specific airline. I have a hash map which stores strings and planes. In my plane class i am implementing Comparable and i have the compareTo method. Could anyone help me achieve using the compareTo method to arrange the planes in descending order to show the next flight. I want to arrange the flights by the variable overdue.
This is the case in the MainApp that i have to use the compareTo on
switch (nextChoice)
{
case 1:
airlineMap.printAirline("Aer Lingus");
break;
case 2:
airlineMap.printAirline("Brittish Airways");
break;
case 3:
airlineMap.printAirline("Eithad");
break;
case 4:
airlineMap.printAirline("Iberia");
break;
case 5:
airlineMap.printAirline("Quantas");
break;
I hope to add the descending order to a airline print: airlineMap.printAirline("Aer Lingus");
Here is my Plane class:
import java.util.LinkedList;
public class Plane implements Comparable
{
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
public Plane(String flightNumber, String airlineName, double fuelRemaining, int overdue, int passengerNumber, AIRPLANETYPE planeType) {
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
}
public String getAirlineName() {
return airlineName;
}
public void setAirlineName(String airlineName) {
this.airlineName = airlineName;
}
public void setOverdue(int overdue) {
this.overdue = overdue;
}
public int getOverdue(){
return overdue;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public int compareTo(Object arg0) {
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.overdue - p.getOverdue());
}
return 0;
}
public String toString() {
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType + ".\n";
}
}
Since HashMap is unordered, you have two ways of going about sorting your planes:
Put them into a sorted container, or
Put them into an ArrayList<Plane> or an array Plane[], and sort that list or array
The first approach can be achieved with a TreeSet<Plane>: put your planes into the set, and iterate them in the "natural" order (i.e. the order consistent with their compareTo method).
The second approach requires copying the planes into a separate container or an array, and then using the sort method (or the Arrays.sort static method if it is an array) to order your planes in accordance with the order set by their compareTo implementation.
EDIT : (based on a comment) One way to deal with a problem of storing planes in a specific order inside a hash map is to make a hash map of tree sets, like this:
Map<String,TreeSet<Plane>> airlineMap = new HashMap<String,TreeSet<Plane>>();
Once you add the planes to each airline, they would be maintained in the order based on your compareTo implementation. with a TreeSet<Plane> in hand, you can easily find the next or the prior Plane by calling higher or lower.
You should use Math.signum rather than Math.ceil in your compareTo method.
What is the best way to use the values stored in an Enum as String literals?
For example:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3
}
Then later I could use Mode.mode1 to return its string representation as mode1. Without having to keep calling Mode.mode1.toString().
You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...
Option One: use the built-in name() on an enum. This is perfectly fine if you don't need any special naming format.
String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.
Option Two: add overriding properties to your enums if you want more control
public enum Modes {
mode1 ("Fancy Mode 1"),
mode2 ("Fancy Mode 2"),
mode3 ("Fancy Mode 3");
private final String name;
private Modes(String s) {
name = s;
}
public boolean equalsName(String otherName) {
// (otherName == null) check is not needed because name.equals(null) returns false
return name.equals(otherName);
}
public String toString() {
return this.name;
}
}
Option Three: use static finals instead of enums:
public final class Modes {
public static final String MODE_1 = "Fancy Mode 1";
public static final String MODE_2 = "Fancy Mode 2";
public static final String MODE_3 = "Fancy Mode 3";
private Modes() { }
}
Option Four: interfaces have every field public, static and final:
public interface Modes {
String MODE_1 = "Fancy Mode 1";
String MODE_2 = "Fancy Mode 2";
String MODE_3 = "Fancy Mode 3";
}
Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?
String name = Modes.mode1.name();
Modes mode = Modes.valueOf(name);
There's also a static valueOf(Class, String) on Enum itself, so you could also use:
Modes mode = Enum.valueOf(Modes.class, name);
You could override the toString() method for each enum value.
Example:
public enum Country {
DE {
#Override
public String toString() {
return "Germany";
}
},
IT {
#Override
public String toString() {
return "Italy";
}
},
US {
#Override
public String toString() {
return "United States";
}
}
}
Usage:
public static void main(String[] args) {
System.out.println(Country.DE); // Germany
System.out.println(Country.IT); // Italy
System.out.println(Country.US); // United States
}
As Benny Neugebauer mentions, you could overwrite the toString(). However instead overwriting the toString for each enum field I like more something like this:
public enum Country{
SPAIN("EspaƱa"),
ITALY("Italia"),
PORTUGAL("Portugal");
private String value;
Country(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public String toString() {
return this.getValue();
}
}
You could also add a static method to retrieve all the fields, to print them all, etc.
Simply call getValue to obtain the string associated to each Enum item
mode1.name() or String.valueOf(mode1). It doesn't get better than that, I'm afraid
public enum Modes {
MODE1("Mode1"),
MODE2("Mode2"),
MODE3("Mode3");
private String value;
public String getValue() {
return value;
}
private Modes(String value) {
this.value = value;
}
}
you can make a call like below wherever you want to get the value as a string from the enum.
Modes.MODE1.getvalue();
This will return "Mode1" as a String.
For my enums I don't really like to think of them being allocated with 1 String each. This is how I implement a toString() method on enums.
enum Animal
{
DOG, CAT, BIRD;
public String toString(){
switch (this) {
case DOG: return "Dog";
case CAT: return "Cat";
case BIRD: return "Bird";
}
return null;
}
}
You can use Mode.mode1.name() however you often don't need to do this.
Mode mode =
System.out.println("The mode is "+mode);
As far as I know, the only way to get the name would be
Mode.mode1.name();
If you really need it this way, however, you could do:
public enum Modes {
mode1 ("Mode1"),
mode2 ("Mode2"),
mode3 ("Mode3");
private String name;
private Modes(String s) {
name = s;
}
}
my solution for your problem!
import java.util.HashMap;
import java.util.Map;
public enum MapEnumSample {
Mustang("One of the fastest cars in the world!"),
Mercedes("One of the most beautiful cars in the world!"),
Ferrari("Ferrari or Mercedes, which one is the best?");
private final String description;
private static Map<String, String> enumMap;
private MapEnumSample(String description) {
this.description = description;
}
public String getEnumValue() {
return description;
}
public static String getEnumKey(String name) {
if (enumMap == null) {
initializeMap();
}
return enumMap.get(name);
}
private static Map<String, String> initializeMap() {
enumMap = new HashMap<String, String>();
for (MapEnumSample access : MapEnumSample.values()) {
enumMap.put(access.getEnumValue(), access.toString());
}
return enumMap;
}
public static void main(String[] args) {
// getting value from Description
System.out.println(MapEnumSample.getEnumKey("One of the fastest cars in the world!"));
// getting value from Constant
System.out.println(MapEnumSample.Mustang.getEnumValue());
System.out.println(MapEnumSample.getEnumKey("One of the most beautiful cars in the world!"));
System.out.println(MapEnumSample.Mercedes.getEnumValue());
// doesnt exist in Enum
System.out.println("Mustang or Mercedes, which one is the best?");
System.out.println(MapEnumSample.getEnumKey("Mustang or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mustang, which one is the best?") + " is the best!.");
// exists in Enum
System.out.println("Ferrari or Mercedes, wich one is the best?");
System.out.println(MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") + " is the best!");
}
}
You can simply use:
""+ Modes.mode1
public enum Environment
{
PROD("https://prod.domain.com:1088/"),
SIT("https://sit.domain.com:2019/"),
CIT("https://cit.domain.com:8080/"),
DEV("https://dev.domain.com:21323/");
private String url;
Environment(String envUrl) {
this.url = envUrl;
}
public String getUrl() {
return url;
}
}
String prodUrl = Environment.PROD.getUrl();
It will print:
https://prod.domain.com:1088/
This design for enum string constants works in most of the cases.
Enum is just a little bit special class. Enums can store additional fields, implement methods etc. For example
public enum Modes {
mode1('a'),
mode2('b'),
mode3('c'),
;
char c;
private Modes(char c) {
this.c = c;
}
public char character() {
return c;
}
}
Now you can say:
System.out.println(Modes.mode1.character())
and see output:
a
package com.common.test;
public enum Days {
monday(1,"Monday"),tuesday(2,"Tuesday"),wednesday(3,"Wednesday"),
thrusday(4,"Thrusday"),friday(5,"Friday"),saturday(6,"Saturday"),sunday(7,"Sunday");
private int id;
private String desc;
Days(int id,String desc){
this.id=id;
this.desc=desc;
}
public static String getDay(int id){
for (Days day : Days.values()) {
if (day.getId() == id) {
return day.getDesc();
}
}
return null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
};
This method should work with any enum:
public enum MyEnum {
VALUE1,
VALUE2,
VALUE3;
public int getValue() {
return this.ordinal();
}
public static DataType forValue(int value) {
return values()[value];
}
public String toString() {
return forValue(getValue()).name();
}
}
i found this one is more easy for preventing type error:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
String str;
Modes(){
this.str = super.name();
}
#Override
#NonNull
public String toString() {
return str;
}
however - this may work when you need to use a String on a log/println or whenever java compiles the toString() method automatically, but on a code line like this ->
// sample method that require (string,value)
intent.putExtra(Modes.mode1 ,shareElement.getMode()); // java error
// first argument enum does not return value
instead as mentioned above you will still have to extend the enum and use .name() in those cases like this:
intent.putExtra(Modes.mode1.name() ,shareElement.getMode());
after many tries I have come with this solution
public static enum Operation {
Addition, Subtraction, Multiplication, Division,;
public String getUserFriendlyString() {
if (this==Addition) {
return " + ";
} else if (this==Subtraction) {
return " - ";
} else if (this==Multiplication) {
return " * ";
} else if (this==Division) {
return " / ";
}
return "undefined";
}
}
You can try this:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
public String toString(){
switch(this) {
case some-really-long-string:
return "some-really-long-string";
case mode2:
return "mode2";
default: return "undefined";
}
}
}
use mode1.name() or String.valueOf(Modes.mode1)
I use the enum to make a few constants:
enum ids {OPEN, CLOSE};
the OPEN value is zero, but I want it as 100. Is it possible?
Java enums are not like C or C++ enums, which are really just labels for integers.
Java enums are implemented more like classes - and they can even have multiple attributes.
public enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.
See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.
Yes. You can pass the numerical values to the constructor for the enum, like so:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
See the Sun Java Language Guide for more information.
whats about using this way:
public enum HL_COLORS{
YELLOW,
ORANGE;
public int getColorValue() {
switch (this) {
case YELLOW:
return 0xffffff00;
case ORANGE:
return 0xffffa500;
default://YELLOW
return 0xffffff00;
}
}
}
there is only one method ..
you can use static method and pass the Enum as parameter
like:
public enum HL_COLORS{
YELLOW,
ORANGE;
public static int getColorValue(HL_COLORS hl) {
switch (hl) {
case YELLOW:
return 0xffffff00;
case ORANGE:
return 0xffffa500;
default://YELLOW
return 0xffffff00;
}
}
Note that these two ways use less memory and more process units .. I don't say this is the best way but its just another approach.
If you use very big enum types then, following can be useful;
public enum deneme {
UPDATE, UPDATE_FAILED;
private static Map<Integer, deneme> ss = new TreeMap<Integer,deneme>();
private static final int START_VALUE = 100;
private int value;
static {
for(int i=0;i<values().length;i++)
{
values()[i].value = START_VALUE + i;
ss.put(values()[i].value, values()[i]);
}
}
public static deneme fromInt(int i) {
return ss.get(i);
}
public int value() {
return value;
}
}
If you want emulate enum of C/C++ (base num and nexts incrementals):
enum ids {
OPEN, CLOSE;
//
private static final int BASE_ORDINAL = 100;
public int getCode() {
return ordinal() + BASE_ORDINAL;
}
};
public class TestEnum {
public static void main (String... args){
for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) {
System.out.println(i.toString() + " " +
i.ordinal() + " " +
i.getCode());
}
}
}
OPEN 0 100
CLOSE 1 101
The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.
Example:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};
Gives the output:
OPEN: 100
CLOSE: 101
OTHER: 102
Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.
#scottf
An enum is like a Singleton. The JVM creates the instance.
If you would create it by yourself with classes it could be look like that
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
#Override
public String toString(){
return enumValue;
}
}
And could be used like that:
public class HelloWorld{
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
#Override
public String toString(){
return enumValue;
}
}
public static void main(String []args){
System.out.println(MyEnum.ONE);
System.out.println(MyEnum.TWO);
System.out.println(MyEnum.ONE == MyEnum.ONE);
System.out.println("Hello World");
}
}
public class MyClass {
public static void main(String args[]) {
Ids id1 = Ids.OPEN;
System.out.println(id1.getValue());
}
}
enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
#scottf, You probably confused because of the constructor defined in the ENUM.
Let me explain that.
When class loader loads enum class, then enum constructor also called. On what!! Yes, It's called on OPEN and close. With what values 100 for OPEN and 200 for close
Can I have different value?
Yes,
public class MyClass {
public static void main(String args[]) {
Ids id1 = Ids.OPEN;
id1.setValue(2);
System.out.println(id1.getValue());
}
}
enum Ids {
OPEN(100), CLOSE(200);
private int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
public void setValue(int value) { id = value; }
}
But, It's bad practice. enum is used for representing constants like days of week, colors in rainbow i.e such small group of predefined constants.
I think you're confused from looking at C++ enumerators. Java enumerators are different.
This would be the code if you are used to C/C++ enums:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};