2017-11-11 40 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 
    } 
} 
相关问题