2014-03-12 15 views
0

我對年齡優先考慮這個問題Java的年齡近似

這些人,是需要處理的輸入

Dude 20-25 Major Injuries 
Guy 48 Panic 
Bob <=4 

我有先後次序誰必須由受害者的年齡被保存(年輕,年長的) 你可以受害者的名字後看到的數字/ s的年齡

所以如果是beetwen 20-25將被視爲20

範圍
  • 如果是< = 4,將被認爲是4
  • 如果是< 4它會被認爲是3
  • 如果是> 4它會被認爲是5

我的問題是,什麼是處理每一行,所以我可以從年齡 我需要將它存儲得到考慮價值的最佳方式回到地方,比如一個數組或ArrayList中 的,所以如果它是:

Dude 20-25 Major Injuries 

它會變成老兄20大受傷

我只是需要想法來處理它,不需要是代碼。

回答

-1

爲了解析年齡,使用String.contains邏輯:

String input = "Bob 20-25"; 
Pattern pattern = 
Pattern.compile("[[(<=?)(>=?)]?[0-9]{1, 2}([0-9]{1,2} - [0-9]{1, 2})]"); 

Matcher matcher = 
pattern.matcher(input); 

String regex = matcher.group(); 
int age = Integer.parseInt(regex); 
if (regex.contains("=") {}; 
else if (regex.contains("<") { 
    age = age - 1; 
else if (regex.contains(">") { 
    age = age + 1; 
} 
else {} 

來存儲數據,一旦你解析年齡,你可以使用一個PriorityQueue

PriorityQueue類提供了一個構造函數,您可以在其中指定自己的比較器來排列隊列中的元素。這是存儲將允許快速檢索和索引的元素的最有效方式。

JavaDocs

+0

我覺得OP是尋找如何解析'<=','<'等 – GriffeyDog

+0

我承擔這三種投入不是唯一可能的投入。使用這種方法會導致你需要〜300個if語句來使其通用。 – Holloway

+0

爲什麼-1?我做了編輯考慮其他年齡不> =,<=, <, > 4和20 - 25 –

0

你可以使用正則表達式,並通過你的規則替換的條款。下面是第一條規則的一個小例子:

String input = "Dude 20-25 Major Injuries"; 
Pattern pattern = Pattern.compile("([^\\d]*)([\\d]+)-([\\d]+)(.*)"); 
Matcher matcher = pattern.matcher(input); 
matcher.matches(); 
String output = matcher.group(1) + matcher.group(2) + matcher.group(4); 
System.out.println(input); 
System.out.println(output); 

OUTPUT:

Dude 20-25 Major Injuries 
Dude 20 Major Injuries 
+0

這一個真的有幫助,它給了我應該使用什麼(正則表達式)的想法,它帶有一個代碼示例(一個工作的非運行時錯誤代碼:))。非常感謝你。 –