我很难确保双打在我的程序中正确验证。用户可以输入一个金额存入账户,这应该是一个双倍(我知道,这不是我应该使用的,但它是分配指南的一部分)。理论上,用户应该可以存入任何金额 - 不只是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的(有双别的东西吗?)
非常感谢
定义'一些问题'。不确定是否因为...而发生了什么?不是一个真正的问题。 – EJP 2013-04-29 10:01:50
我真的很讨厌那些告诉我一个变量被设置为'true'的意见:'// set bolSuccessful and bolNumeric as true' – Henrik 2013-04-29 10:04:22
我也讨厌这些评论 - 但就像我说的,这是一个任务。我刚刚被告知要疯狂发表评论。 – 2013-04-29 10:05:20