2017-11-11 95 views
3

我想檢查一下數字是否出現在我的字符串末尾,然後將此數字(一個id)傳遞給我的函數。以下是我認識的那一刻:檢查一個整數是否出現在我的字符串的末尾?

String call = "/webapp/city/1"; 
String pathInfo = "/1"; 


    if (call.equals("/webapp/city/*")) { //checking (doesn't work) 
      String[] pathParts = pathInfo.split("/"); 
      int id = pathParts[1]; //desired result : 1 
      (...) 
    } else if (...) 

錯誤:

了java.lang.RuntimeException:錯誤:/ web應用/城市/ 1

+0

使用了合適的工具:JAX-RS,Spring的MVC,的Restlet,或任何REST框架。但是,你的代碼沒有意義:/ webapp/city/*不可能**等於**/webapp/city/1。最後一個字符顯然不一樣。而一個String數組包含Strings,所以它的第二個元素不可能是一個int。 –

回答

2

您可以使用matches(...) method of String檢查

if (call.matches("/webapp/city/\\d+")) { 
    ... //      ^^^ 
     //      | 
     // One or more digits ---+ 
} 

一旦你得到一個匹配,Y:如果你的字符串匹配給定模式OU需要得到split的元素[2],並使用Integer.parseInt(...)方法解析爲一個int

int id = Integer.parseInt(pathParts[2]); 
1
final String call = "http://localhost:8080/webapp/city/1"; 
int num = -1; //define as -1 

final String[] split = call.split("/"); //split the line 
if (split.length > 5 && split[5] != null) //check if the last element exists 
    num = tryParse(split[5]); // try to parse it 
System.out.println(num); 

private static int tryParse(String num) 
{ 
    try 
    { 
     return Integer.parseInt(num); //in case the character is integer return it 
    } 
    catch (NumberFormatException e) 
    { 
     return -1; //else return -1 
    } 
} 
相關問題