I need some hints on this: I have lets say a list or a sequence of years with
int startYear = 2010;
int endYear = 2050;
and i have an enum with letters and digits as year codes.
I need this for Barcode generation where i have a timestamp that need to be coded into 3 digits/letters, so i need to map year month and day to a code position.
What i need to do is to map the year sequence to the codes list into a HashMap of keys (the year numbers) and values (the year codes),
but obviously the codes list is not as long as the year sequence so i need to check when the last index is reached and if yes i need to reloop through the codes list until the end of the year sequence is reached.
what i need to achieve is this:
year code
2012 C
2013 D
.
.
2030 Y
2031 1
.
.
2039 9
2040 A
and so on...
unfortunately i could not figure out a way how to do this, couse I'm pretty new to java so I'd appreciate if someone can give me some advice..
Simply use the %
operator to calculate the code index
List years = ...
List codes = ...
for (int i = 0, yearsSize = years.size(), codesSize = codes.size(); i < yearsSize; i++) {
map.put(years.get(i), codes.get(i % codesSize));
}
See Remainder Operator (%) .
How about something like this?:
Assuming:
public enum Code {
A, B, C, ... Z, 1, ... 9;
}
List<Integer> years;
HashMap<Integer,Code> map;
Just add an index for the code which will initialize if too big:
int i = 0;
for(Integer year : years) {
map.push(year, Code.values()[i];
i++;
if(i >= Code.values().length) {
i = 0;
}
}
Before encoding the year, modulous the year so the %year% loops:
int yearToEncode = 2012 + ((year - 2012) % MyEnum.values().length);
Assuming that 2012
is "year zero".
Then you can use:
MyEnum encodedYear = MyEnum.values()[yearToEncode - 2012];
But your code would be a whole lot simpler if year zero was arbitrary:
MyEnum[] codes = MyEnum.values();
MyEnum encodedYear = codes[year % codes.length];
try this you can even change the start year and end year
int yStart = 2010;
int yEnd = 2050;
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int pos = 0;
for(int i = yStart; i < yEnd; i++){
pos = (i - yStart)%s.length();
map.put(i, s.substring(pos, pos+1));// put in map
System.out.println(i + " " + s.substring(pos, pos+1));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.