Remove character from integer

元气小坏坏 提交于 2020-01-05 06:44:25

问题


FileDataModel accepts data in the format

 userId,itemId,pref(long,long,Double).

At the moment I have some itemId that consist of an 'x' at the end of the number. How do I edit the some of the itemID such that it removes the 'x' ? Is it possible to do this with a simple try catch statement?

DataModel model = null;
try{
    model = new FileDataModel(new File("book_data/BX-Book-Ratings.csv"));

}catch(NumberFormatException e){
    REMOVE X


}

CODE:

DataModel model = new FileDataModel(new File("book_data/BX-Book-Ratings.csv"));

ERROR:

Exception in thread "main" java.lang.NumberFormatException: For input string: "034545104X"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:589)
    at java.lang.Long.parseLong(Long.java:631)

DATA:

276725,034545104X,0
276726,155061224,5
276727,446520802,0
276729,052165615X,3

回答1:


One way would be to run a pre-processor on the file that transforms it's content to ensure it is compatible with FileDataModel. If your data format is very simple you may just use a regular expression replace. Otherwise I'd suggest having a parser that can bring the data into memory, then perform your manipulation with a transformer and finally save back the results with a serializer.

Something like:

File file = new File("book_data/BX-Book-Ratings.csv");
FileDataModelTransformer transformer = new FileDataModelTransformer();
transformer.transformInPlace(file);
DataModel model = new FileDataModel(file);

By the way, it's more flexible to rely on streams or buffers than File.




回答2:


The easiest way, IMHO, would be to just use an if statement:

String itemIdStr = "034545104X"; // for example
if (itenIdStr.endsWith("X")) {
    itemIdStr = itemIdStr.substring(0, itemIdStr.length() - 1);
}
long itemId = Long.parseLong(itemIdStr);


来源:https://stackoverflow.com/questions/40196498/remove-character-from-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!