對於我需要編寫的程序,我必須確保用戶給我一個迴文形式的五位數字。該程序必須檢查以確保該數字是迴文,如果不是,它會給出錯誤。如何向用戶詢問Java中的五位輸入?
有沒有人有任何想法如何做這樣的事情?如果有幫助,我正在使用Eclipse。
大多數情況下,我只需要幫助,確保提供給該程序的號碼只有五位數,不多也不少。
對於我需要編寫的程序,我必須確保用戶給我一個迴文形式的五位數字。該程序必須檢查以確保該數字是迴文,如果不是,它會給出錯誤。如何向用戶詢問Java中的五位輸入?
有沒有人有任何想法如何做這樣的事情?如果有幫助,我正在使用Eclipse。
大多數情況下,我只需要幫助,確保提供給該程序的號碼只有五位數,不多也不少。
如果你把它當作一個整數:
int n = getUserInput();
// Number is not 5 digits.
if (n/10000>=10 || n/10000<=0)
throw new Exception();
// First and last digits don't match.
if (n%10 != n/10000)
throw new Exception();
// Second and fourth digits don't match.
if ((n%100)/10 != (n/1000)%10)
throw new Exception();
如果你有它作爲一個字符串:
String s = getUserInput();
// Test that pin is number.
for (int i=0;i<s.length();i++) {
if (c < '0' || c > '9') // or `if (!Character.isDigit(c))`
throw new Exception();
}
// String is not 5 characters.
if (s.length() != 5)
throw new Exception();
// First and last don't match.
if (s.charAt(0) != s.charAt(4))
throw new Exception();
// Second and fourth don't match
if (s.charAt(1) != s.charAt(3))
throw new Exception();
使用'regex'或其他方法檢查它是否是5位數字,然後使用上面的鏈接查看它是否是迴文。 – AntonH
說實話,我很確定,當我檢查迴文時,我可以告訴程序需要檢查數字1和數字5是否相同,以及數字2和數字4是否相同。 – user3348422
嘗試以字符串形式讀取它,檢查字符串的長度,然後檢查每個字符是否是數字。應該可以按照鏈接@AntonH張貼 – EyeOfTheHawks