2013-10-18 75 views
-2

我需要幫助編寫一個方法來檢查數字和文本是否連續。如果像輸入的deFgh或456789這樣的輸入和其他任何不連續的輸入都需要返回布爾值true。我不明白如何使循環對於像xyZaBcD和890123或cbazyx創建一個布爾方法來檢查連續的數字

+2

你試過了什麼?你有一些代碼嗎? –

+0

您可以掃描文本並保持標誌,意思是「所有字符都是數字到目前爲止」,「所有字符都是迄今爲止的字母」。希望有所幫助。 – Vlad

+1

嘗試自己做功課。這就是它被稱爲作業的原因。別擔心,這很有趣。如果你嘗試在互聯網上找到解決方案。有很多,相信我。如果您的實施有特定問題,請返回此處。 – AlexR

回答

0

這樣的情況是正確的。只需遍歷字符串並檢查char代碼的序列即可。如果需要,請使用toLowerCase()方法。

+0

您需要知道在哪裏迴環,並循環回。這對字母和數字會有所不同。 – Cruncher

1

試試這個代碼:

public static boolean isConsecutive(final String s) throws IllegalArgumentException 
{ 
    if (null == s) throw new IllegalArgumentException(); 
    if (s.length() <= 1) return true; 

    final String lc = s.toLowerCase(); 
    char c = lc.charAt(0); 
    for (int cc=1; cc<lc.length(); cc++) 
     if ((c+1) != lc.charAt(cc)) 
      return false; 
     else 
      c++; 

    return true; 
} 

public static void main(String[] args) 
{ 
    try 
    { 
     System.out.println(isConsecutive("456789")); 
     System.out.println(isConsecutive("deFgh")); 
     System.out.println(isConsecutive("xyZaBcD")); 
     System.out.println(isConsecutive("890123")); 
    } 
    catch(final Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

但我真的建議你不要把它給老師,因爲這將有更多的問題,只使用它作爲指導自己的代碼

0

可以投(int)給循環中的字符。如果整數介於48和57之間,則表示該字符是數字。

請參閱ASCII表格,以查看char從鑄造中給出的整數。

+0

你可以通過添加示例代碼來改善這一點,並確保你的術語是精確的(「你可以將字符轉換爲int」會更清晰)。 –

1

這可以在最簡單的方法來實現:

public class Check { 
    private static boolean checkConsecutive(String str) { 
      str = str.toLowerCase(); 
      if (str.length() == 1) return true; 

     for (int i = 1; i < str.length(); i++) { 
      String first = str.substring(i, i+1); 
      String beforeFirst = str.substring(i-1, i); 

      if (beforeFirst.compareTo(first) > 0) { 
       return false; 
      } 
     } 

     return true; 
    } 

    public static void main(String[] args) { 
     Check obj = new Check(); 

     System.out.printf("abcdef is: %s%n", obj.checkConsecutive("abcdef")); 
     System.out.printf("12345 is: %s%n", obj.checkConsecutive("12345")); 
     System.out.printf("54321 is: %s%n", obj.checkConsecutive("54321")); 
     System.out.printf("fedcba is: %s%n", obj.checkConsecutive("fedcba")); 
    } 
} 

輸出將是下一個:

abcdef is: true 
12345 is: true 
54321 is: false 
fedcba is: false 

此行str.substring(i, i+1)返回一個信,我們可以使用來自String類compareTo()它比較連續通過它自己。

+0

@ user2896303爲什麼你在這種情況下不接受這個答案? –