Java 如何将字符串解释为负数或零并相应地抛出?

Java 如何将字符串解释为负数或零并相应地抛出?,java,guava,preconditions,Java,Guava,Preconditions,我有一个方法,在这个方法中,我接受一个字符串,这个字符串可以是数字,也可以是普通字符串 public Builder setClientId(String clientId) { checkNotNull(clientId, "clientId cannot be null"); checkArgument(clientId.length() > 0, "clientId can't be an empty string"); this.clientId = cli

我有一个方法,在这个方法中,我接受一个字符串,这个字符串可以是数字,也可以是普通字符串

public Builder setClientId(String clientId) {
    checkNotNull(clientId, "clientId cannot be null");
    checkArgument(clientId.length() > 0, "clientId can't be an empty string");
    this.clientId = clientId;
    return this;
}
现在我想添加一个检查,假设有人将
clientId
作为负数
“-12345”
或零
“0”
传递,那么我想解释这一点并抛出
IllegalArgumentException
,消息为
“clientId不能是负数或零作为数字”
,或者可能是其他一些好消息。如果可能,我如何使用番石榴先决条件来实现这一点

根据建议,我使用以下代码:

public Builder setClientId(String clientId) {
    checkNotNull(clientId, "clientId cannot be null");
    checkArgument(clientId.length() > 0, "clientId can't be an empty string");
    checkArgument(!clientid.matches("-\\d+|0"), "clientid must not be negative or zero");
    this.clientId = clientId;
    return this;
}

有更好的方法吗?

我认为最简单的方法如下:

 public Builder setClientId(String clientId) {
    final Integer id = Ints.tryParse(clientId);
    checkArgument(id != null && id.intValue() > 0,
      "clientId must be a positive number, found: '%s'.", clientId);
    this.clientId = clientId;
    return this;
  }
调用此方法时,将提供:

.setClientId("+-2"); 
// java.lang.IllegalArgumentException: clientId must be a positive number, found: '+-2'.

.setClientId("-1"); 
// java.lang.IllegalArgumentException: clientId must be a positive number, found: '-1'.

.setClientId(null); 
// java.lang.NullPointerException
此代码使用。从JavaDoc:

返回:

string
表示的整数值,如果
string
的长度为零或无法解析为整数值,则为
null

此外,当接收到
null
时,它会抛出
NullPointerException


编辑:但是,如果允许任何其他字符串,代码将更改为:

public Builder setClientId(String clientId) {
    checkArgument(!Strings.isNullOrEmpty(clientId),
      "clientId may not be null or an empty string, found '%s'.", clientId);
    final Integer id = Ints.tryParse(clientId);
    if (id != null) {
      checkArgument(id.intValue() > 0,
        "clientId must be a positive number, found: '%s'.", clientId);
    }
    this.clientId = clientId;
    return this;
  }

此代码将接受严格正整数或非空且非空的所有字符串。

如果(clientId.matches(“-\\d+|0”)抛出新的IllegalArgumentException(“clientId不能为负数或零作为数字”);
为什么你不能解析它并检查它不是一个数字或不是一个负数?因此,
-10
应该被拒绝,但
-1O
应该被接受?(零位与字母oh)@可悲的是,我想看看是否有更好的方法可以在一行中实现这一点,而不必写大的if else尝试catch block。你可以使用正则表达式@saka129 give,但实际的解析对Meals来说似乎更具可读性。因此,我的要求是,如果clientId是一个正确的字符串,那么我也想允许这样做。所以基本要求是-
clientId
可以是一个数字,如果是,那么它应该是大于零的正数,
clientId
也可以是普通字符串。我添加了第二个版本,它也允许普通字符串。谢谢,看起来不错。没有使用整数作为id,有像
Longs.tryParse这样的长吗
因为clientId可以是Long而不是整数。是的,Longs.tryParse和Doubles.tryParse存在,因此您可以使用您喜欢的一个。您使用的是Guava 14或更高版本吗?这是。