我很難確保雙打在我的程序中正確驗證。用戶可以輸入一個金額存入賬戶,這應該是一個雙倍(我知道,這不是我應該使用的,但它是分配指南的一部分)。理論上,用戶應該可以存入任何金額 - 不只是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