我很难确保在我的程序中正确验证双打。用户可以输入要存入帐户的金额,该金额应该是双倍的(我知道,这不是我应该使用的,但它是分配指南的一部分)。从理论上讲,用户应该能够存入任何金额——不仅仅是 30 英镑,而是 15.23 英镑。这是我目前拥有的验证,它允许数字,但阻止输入句号,这会产生许多问题。
这是我到目前为止的代码:
public static String getBalanceValidation()
{
//Allow user input capabilities
Scanner input = new Scanner (System.in);
//Declare variables needed for validation
double dblInput = 0; //dblInput is set as 0
String strNumber = ""; //strNumber is blank
boolean bolSuccessful, bolNumeric;
int intCount;
char charLetter;
do
{
//set bolSuccessful and bolNumeric as true
bolSuccessful = true;
bolNumeric = true;
try //try user input
{
System.out.println("Enter the balance to be deposited: "); //User prompt
strNumber = input.next(); //User input as string
dblInput = Double.parseDouble(strNumber) ; //String input converted to double
}// end of try
catch (NumberFormatException e) //NumberFormatException disallows letters or symbols in value
{
System.out.println("Deposit value cannot contain letters!"); //Error message
bolSuccessful = false; //set bolSuccessful as false
continue; //Return to try
}//end of number format catch
//create for loop which checks each character throughout the string
for (intCount = 0; intCount < strNumber.length(); intCount++)
{
charLetter = strNumber.charAt(intCount); //charLetter is the alphanumeric value of a character in the string at the point dictated by intCount
if (!(charLetter >= '0') && (charLetter <= '9' ) //if charLetter is not between 0 and 9
|| (charLetter == '.')) //or charLetter is not a full stop
{
bolNumeric = false; //Set bolNumeric as false
}//end of if construct
}//end of for loop
if (!bolNumeric) //if bolNumeric is false
{
System.out.println("Incorrect input format! The balance must be numbers only!"); //Error message
bolSuccessful = false; //Set bolSuccessful as false
}//end of if construct
}while (!bolSuccessful); //While bolSuccessful is false, return to top
return strNumber; //return strNumber to be used in main method
//end of do method
}//end of getBalanceValidation method
我不确定是否是因为我使用了 NumberFormatException (还有其他的东西吗?)
非常感谢