2014-05-22 21 views
-2

對於我需要編寫的程序,我必須確保用戶給我一個迴文形式的五位數字。該程序必須檢查以確保該數字是迴文,如果不是,它會給出錯誤。如何向用戶詢問Java中的五位輸入?

有沒有人有任何想法如何做這樣的事情?如果有幫助,我正在使用Eclipse。
大多數情況下,我只需要幫助,確保提供給該程序的號碼只有五位數,不多也不少。

+0

使用'regex'或其他方法檢查它是否是5位數字,然後使用上面的鏈接查看它是否是迴文。 – AntonH

+0

說實話,我很確定,當我檢查迴文時,我可以告訴程序需要檢查數字1和數字5是否相同,以及數字2和數字4是否相同。 – user3348422

+0

嘗試以字符串形式讀取它,檢查字符串的長度,然後檢查每個字符是否是數字。應該可以按照鏈接@AntonH張貼 – EyeOfTheHawks

回答

3

如果你把它當作一個整數:

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(); 
+0

不知道我推薦這個。如果輸入必須是五位數字,是否允許以0開頭(例如02420)?認爲將輸入視爲「String」而不是「int」。 – ajb

+0

你可能不想拋出異常,因爲OP會在那裏和那裏處理消息。另外,他/他可能不知道什麼是異常。 – nrubin29

+0

顯然,你不會拋出這樣的例外,但這個想法仍然存在...... –

4
  • 閱讀您的數據串
  • ,如果它僅包含數字檢查(如果你使用正則表達式,你也可以檢查長度,如matches("\\d{5}")
  • 檢查是否爲pa通過比較杉樹字符與第五和第二與第四(你可以使用charAt(index))。
+0

使用字符串而不是整數。 -1不提供詳細信息或代碼片段(尚未)。總而言之,+0。 – nrubin29

+4

@ nrubin29我懷疑這個問題是作業,所以我不想給OP完整的工作代碼。相反,部分指針應該足以解決這個問題。無論如何感謝您的意見。 – Pshemo

+1

@ nrubin29那麼他漂亮的算法。 OP可以很容易地編寫程序。 +1對我來說,沒有必要給所有的代碼。 –