2012-08-04 47 views
1

我試圖計算出現在一個java字符串中的字符數。檢查一個Java字符串中的字符數是否正確

例如:

給出的牌手6S/3D/2H/13C /廣告

多少次/字符出現? = 4

用戶可以輸入不同數量的卡片變量,因此硬編碼檢查出現次數的方法將不起作用。

分隔符可以是以下任何一個: - /空格(一個手中只允許使用一個分隔符類型)。 所以我需要能夠檢查分隔符是否出現4次,否則就給出了不正確的格式。

這裏的一些Java代碼給的什麼,我試圖做一個更好的主意:

String hand = "6s/1c/2H/13c/Ad"; 
    System.out.println("Original hand: " + hand); 

    // split the hand string into individual cards 
    String[] cards = hand.split(hand); 

    // Checking for separators 
    // Need to check for the correct number of separators 
    if(hand.contains("/")){ 
     cards = hand.split("/"); 
    } else if (hand.contains("-")){ 
     cards = hand.split("-"); 
    } else if (hand.contains(" ")){ 
     cards = hand.split(" "); 
    } else { 
     System.out.println("Incorrect format!"); 

    } 

任何幫助將是巨大的!

另外這是一個學校項目/作業。

編輯1 -------------------------------------------- ------------所以這裏

確定是我的代碼你的建議後

String hand = "6s 1c/2H-13c Ad"; 
    System.out.println("Original hand: " + hand); 

    // split the hand string into individual cards 
    String[] cards = hand.split("[(//\\-\\s)]"); 

    if (cards.length != 5) { 
     System.out.println("Incorrect format!");  
    } else { 

     for (String card : cards) { 
      System.out.println(card); 
     } 
    } 

上面給出的手是不正確的格式,因爲用戶只能使用一種類型的一個給定的手的分離器。例如:

  • 6S/1C/2H/13C /廣告 - 正確
  • 6S-1C-2H-13C-信息 - 正確
  • 6S 1C 2H 13c的信息 - 正確

我如何確保用戶只使用一種類型的分隔符?

到目前爲止的答案歡呼!

編輯2 ------------------------------------------

所以玩弄嵌套的if語句我的代碼現在看起來像這樣:

String hand = "6s/1c/2H/13c/Ad"; 
    System.out.println("Original hand: " + hand); 

    // split the hand string into individual cards 

    if(hand.contains("/")){ 
     String[] cards = hand.split("/"); 
     if(cards.length != 5){ 
      System.out.println("Incorrect format! 1"); 
     } else { 
      for (String card : cards) { 
       System.out.println(card); 
      } 
     } 

    } else if(hand.contains("-")){ 
     String[] cards = hand.split("-"); 
     if(cards.length != 5){ 
      System.out.println("Incorrect format! 2"); 
     } else { 
      for (String card : cards) { 
       System.out.println(card); 
      } 
     } 

    } else if(hand.contains(" ")){ 
     String[] cards = hand.split(" "); 
     if(cards.length != 5){ 
      System.out.println("Incorrect format! 3"); 
     } else { 
      for (String card : cards) { 
       System.out.println(card); 
      } 
     } 
    } else { 
     System.out.println("Incorrect format! 4"); 
    } 

這樣按預期工作,但醜!

任何建議將是偉大的歡呼聲。

+1

由於這是功課,只是一個提示。 'split'方法允許正則表達式,這可以解決你的問題。請參閱http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum – home 2012-08-04 06:17:10

+0

謝謝。我一直在嘗試使用正則表達式,但如果給定的手改變了,它似乎不起作用。例如,用戶可以輸入AS/13D/JS/13S/AD,這在分隔符出現的地方發生改變。但在說這可能是我做我的正則表達式的方式。乾杯。 – FreshWaterJellyFish 2012-08-04 06:22:05

+0

@ user1575658你試過了什麼正則表達式? – assylias 2012-08-04 06:26:49

回答

0

我在第一個問題編輯之前寫了這個,所以我回應了原始問題而不是它的附錄問題。

documentation on String.split中,不清楚空字符串是否算作子字符串。請注意,"--".split("-").length == 0。這個問題可能會隱含地保證兩個或多個字符將分隔符分開,但這是一個有風險的假設,並且Java的String.split會變成問題。

這是部分更簡單的實現:

char[] delims = {'/', ' ', '-'}; 
    int result = 0; 
    for (char delim : delims) { 
     for (int i = 0; i < hand.length(); i++) { 
      if (hand.charAt(i) == delim) { 
       ++result; 
      } 
     } 
    } 

的完整代碼如下,供功課編輯意見。

interface Counter { 
    int count(String hand); 
} 
class FirstCounter implements Counter { 
    public int count(String hand) { 
     String[] cards = hand.split(hand); 
     if(hand.contains("/")){ 
      cards = hand.split("/"); 
     } else if (hand.contains("-")){ 
      cards = hand.split("-"); 
     } else if (hand.contains(" ")){ 
      cards = hand.split(" "); 
     } else { 
      // Prefer to fail fast unless your requirement 
      // really is to only print "incorrect format" 
      //System.out.println("Incorrect format!"); 
      throw new RuntimeException("Incorrect format!"); 
     } 
     if (hand.endsWith("-") || hand.endsWith("/") || hand.endsWith(" ")) { 
      return cards.length; 
     } 
     return cards.length - 1; 
    }  
} 
class SecondCounter implements Counter { 
    public int count(String hand) { 
     char[] delims = {'/', ' ', '-'}; 
     int result = 0; 
     for (char delim : delims) { 
      for (int i = 0; i < hand.length(); i++) { 
       if (hand.charAt(i) == delim) { 
        ++result; 
       } 
      } 
     } 
     if (result == 0) { 
      // This is a hack or inconsistent with requirements, 
      // but necessary to match original posted code behavior 
      throw new RuntimeException("Incorrect format!"); 
     } 
     return result; 
    } 
} 
class Main { 
    private static int testCount = 0; 

    static void realAssert(boolean condition) { 
     if (!condition) { 
      throw new AssertionError("Java has no real assert"); 
     } 
    } 

    static void test(Counter counter) { 
     ++testCount; 
     try { 
      realAssert(counter.count("6s/3d/2H/13c/Ad") == 4); 
      realAssert(counter.count("6s-3d-2H-13c-Ad") == 4); 
      realAssert(counter.count("6s 3d 2H 13c Ad") == 4); 
      // Don't forget boundary conditions 
      realAssert(counter.count("6s-3d-2H-13c-") == 4); 
      realAssert(counter.count("6s/3d/2H/13c/") == 4); 
      realAssert(counter.count("6s 3d 2H 13c ") == 4); 
      realAssert(counter.count("-6s-3d-2H-13c-") == 5); 
      realAssert(counter.count("/6s/3d/2H/13c/") == 5); 
      realAssert(counter.count(" 6s 3d 2H 13c ") == 5); 
      realAssert(counter.count("--") == 2); 
      // Remember to test error conditions 
      try { 
       counter.count("foobar"); 
       realAssert(false); 
      } catch (RuntimeException e) { 
       // Catching RuntimeException is normally bad 
       // done only as example. 
       // Also normally bad, this is an empty catch 
       // block. These are sometimes useful, but always 
       // at least add a comment that explains that this 
       // catch block really should be empty, in this case 
       // because the test was meant to throw an Error. 
      } 
      try { 
       counter.count("foo/bar-baz"); 
       // Left as exercise for reader, based on question 
       // it is possible this should be disallowed. 
       //realAssert(false); 
      } catch (RuntimeException e) { 
       // Ditto above, intentionally empty catch 
      } 
      System.out.println("Test " + testCount + " succeeded"); 
     } 
     catch (Error e) { 
      // XXX: Don't catch Error in non-example code 
      System.out.println("Test " + testCount + " failed"); 
      /* Normally don't use printStackTrace either */ 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) { 
     test(new FirstCounter()); 
     test(new SecondCounter()); 
    } 
} 

只是爲了教育,正則表達式的方法可以很好。整個解決方案需要一行Ruby,hand.split(/[\-\/ ]/, -1).length - 1

+0

邪惡!非常有幫助的歡呼聲。 – FreshWaterJellyFish 2012-08-04 10:18:48

0

使用regex

如:

String reg = new String(); 
String s = "hjhjhkello/hi"; 
Pattern pattern = Pattern.compile("[(/-\\\\s)]"); // Will find for/or - or space 
Matcher matcher = pattern.matcher(s); 

while(matcher.find()){ 

reg = matcher.group()); 

} 


String[] arr = hand.split(reg); 
+2

我相信我們不應該爲「家庭作業」問題提供完整的答案......一個提示就足夠了。 – SiB 2012-08-04 06:25:45

1

不放棄的答案,你要指定的分隔符split這樣的字符串數組返回的模樣:

cards[0] = "6s" 
cards[1] = "1c" 
cards[2] = "2H" 
. 
. 
. 

在您特定的手中字符串中,您可以爲每張卡片分配一個方便的分隔符用來實現這個...

0

hand.split(hand)將無法​​正常工作。正如@home所說的,你應該在正則表達式中分割輸入字符串。瞭解正則表達式不必(也不應該)匹配整個輸入字符串 - 它應該匹配任何個人分隔符。這就是String.split在傳遞正則表達式時的工作原理 - 正則表達式匹配的每個地方都被看作分隔符,匹配的部分作爲數組返回。

所以:試着寫一個正則表達式來匹配任何一個分隔符。然後,檢查返回的數組是否具有正確數量的元素。如果該陣列被稱爲hand,那麼可以使用hand.length

相關問題