[英]Java - include negative values in 'catch' block for Double.parseDouble()
I have a Java client application that can send a message to the server. 我有一个Java客户端应用程序,可以将消息发送到服务器。 I am setting up input validation so the client detects whether an acceptable message has been sent on the 'send' button-click.
我正在设置输入验证,以便客户端检测是否已在“发送”按钮单击上发送了可接受的消息。
The messages that should be accepted are anything that can be parsed to a double, or a number of selected strings (recognised by the string.equals()
method). 应该接受的消息是任何可以解析为double或许多选定字符串的字符串(由
string.equals()
方法识别)。
I test for the strings first, and if the condition is not met, I try to parse the message to double ( Double.parseDouble(message)
). 我首先测试字符串,如果不满足条件,则尝试将消息解析为double(
Double.parseDouble(message)
)。 At this point, I have a try/catch
block that recognises any failed attept to parse to double (meaning it must contain letters and is therefore invalid), that catches the NumberFormatException
and allows the user a chance to re-enter the message. 在这一点上,我有一个
try/catch
块,该块可以识别要解析为两倍的任何失败的尝试(这意味着它必须包含字母,因此是无效的),它捕获NumberFormatException
并为用户提供了重新输入消息的机会。
I would now like to make it so that the number cannot be negative, and would like to include this in the same try/catch
block so that any negative value can give the user the same opportunity to re-enter. 我现在想使它不能为负数,并希望将其包含在同一
try/catch
块中,以便任何负值都可以为用户提供重新输入的相同机会。
Here is what I currently have: 这是我目前拥有的:
else
{
try
{
//convert number to double (monetary value)
bidAmount = Double.parseDouble(messageToServer);
//send to server with item code
output.println(selectedItemCode + bidAmount);
}
//item cannot turned to double
catch (NumberFormatException numfEx)
{
//inform user
fromServer.setText("Invalid Request!"
+ USER_PROMPT);
}
}
//clear input field for subsequent entry
toServer.setText("");
Can anyone point me in the direction of how to implement this rule, without code duplication if at all possible? 谁能指出我如何实施此规则的方向,如果可能的话,无需代码重复?
Thanks, Mark 谢谢马克
After bidAmount = Double.parseDouble(messageToServer);
在
bidAmount = Double.parseDouble(messageToServer);
, we need to add the following: ,我们需要添加以下内容:
if(bidAmount < 0){
throw new NumberFormatException("Invalid amount");
}
An alternate solution (and probably, best practice) would be to modify catch block to catch IllegalArgumentException
and throw IllegalArgumentException
if the amount is less than 0 as shown below: 另一种解决方案(可能是最佳实践)是修改catch块以捕获
IllegalArgumentException
,如果数量小于0,则抛出IllegalArgumentException
,如下所示:
try
{
//convert number to double (monetary value)
bidAmount = Double.parseDouble(messageToServer);
if(bidAmount < 0){
throw new IllegalArgumentException("Invalid amount");
}
//send to server with item code
output.println(selectedItemCode + bidAmount);
}
//item cannot turned to double
catch (IllegalArgumentException numfEx)
{
//inform user
fromServer.setText("Invalid Request!"
+ USER_PROMPT);
}
Create a separate method which parses the String to a Double and then checks if it is non-negative, returning null in either invalid case. 创建一个单独的方法,该方法将String解析为Double,然后检查它是否为非负数,在两种情况下均返回null。
//convert number to double (monetary value)
bidAmount = getDouble();
if(bidAmount != null) {
//send to server with item code
output.println(selectedItemCode + bidAmount);
toServer.setText("");
} else {
//item cannot turned to double
//inform user
fromServer.setText("Invalid Request!"
+ USER_PROMPT);
}
private Double getDouble() {
try {
double d = Double.parseDouble(messageToServer);
if(d >= 0) {
return d;
}
} catch (NumberFormatException numfEx) {}
return null;
}
Edit: to say if you are opposed to using null values you could also change the method to return a default negative value, say -1, and then change the condition to check if the double is negative instead of null. 编辑:说如果您反对使用空值,您还可以更改方法以返回默认的负值,例如-1,然后更改条件以检查double是否为负而不是null。
This can be achieved without relying on exceptions to control the flow of your program, which is generally a bad idea - see discussion here 无需依赖异常来控制程序流就可以实现此目的,这通常是个坏主意-请参阅此处的讨论
else {
// using a tempBidAmount as I don't have enough context to know whether
// I could just assign the output of parseUserDouble directly to bidAmount
// without causing issues
Double tempBidAmount = parseUserDouble(messageToServer);
if (tempBidAmount != null && tempBidAmount > 0.0) {
bidAmount = tempBidAmount;
output.println(selectedItemCode + bidAmount);
} else {
fromServer.setText("Invalid Request!" + USER_PROMPT);
}
}
toServer.setText("");
....
private Double parseUserDouble(Sting userInput) {
try {
return Double.parseDouble(userInput);
}
catch (NumberFormatException numfEx) {
// consider logging here
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.