I am having trouble with my database where I want to select from a range of stock (not a primary key) and assign them to the users in the system.
For example, I have a field called stockCodes which consists of codes like CAB001-CAB100. This is not the primary key, and the primary key is in fact stockID.
The table looks like this...
ID | Stock Codes
--------------------
1 | CAB001-CAB100
2 | CBA100-CBA200
Now, how do I break down the stock codes so that I get a list like this in Java...
CAB001
CAB002
CAB003
CAB004
CAB005
...
Please help.
You would have to parse the text -- do they always follow the same format of 3 letters and 3 digits? If so, something to this effect would work:
/**
* Populate a full list of stocks from a given range
*
* @param stockRange the stock range pulled from the DB, in this format: "XXX###-XXX###"
* @return list of all stocks in the specified range
*/
public List<String> getFullStockRange(final String stockRange) {
final String[] values = stockRange.split("-");
final Integer first = Integer.parseInt(values[0].substring(3));
final Integer last = Integer.parseInt(values[1].substring(3));
final String prefix = values[0].substring(0, 3);
final List<String> list = new LinkedList<>();
for (int i = first; i<= last; i++) {
final String entry = String.format("%s%03d", prefix, i);
list.add(entry);
}
return list;
}
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.