2012-08-04 86 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

相关问题