【问题标题】:Counting frequency of three letter words三个字母单词的计数频率
【发布时间】:2014-03-16 21:21:02
【问题描述】:

我正在尝试打印字符串中三个字母单词的数量。下面的代码输出字符串中 0-3 个字母单词的数量。

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);

    System.out.println("Input a string:"); 
       String s;
          s = input.nextLine();

     String[] strings = s.split(" ");
     int[] counts = new int[4];
     for(String str : strings)
          if(str.length() < counts.length) counts[str.length()] += 1;
     for(int i = 1; i < counts.length; i++)
         System.out.println(i + " letter words: " + counts[i]); 

     input.close();

    // TODO Auto-generated method stub

   }//end main

}//end class

如何修改此代码以仅显示三个字母单词的数量?有什么想法吗?

【问题讨论】:

  • 这是你的代码吗?如果你写了这个,那么你应该已经知道如何解决这个问题了,不是吗?顺便说一句,确保将所有循环和控制块(例如 if 块)放在花括号中,即使主体只有一行长。在你编程生涯的这个阶段,这样做会在未来拯救你的尾巴,相信我。
  • 这是我们在课堂上所做的修改后的代码。感谢您的建议,我被教导不要将大括号用于单行块。但现在将实施它!
  • 问题是,如果您稍后将单行 if 块更改为两行或多行,但忘记添加花括号,您的逻辑就会被破坏。您的问题的答案在您的在线if(str.length() &lt; counts.length) counts[str.length()] += 1; 上。使用== 而不是&lt;

标签: java string


【解决方案1】:
public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);

    System.out.println("Input a string:"); 
       String s;
          s = input.nextLine();

     String[] strings = s.split(" ");
     int[] counts = new int[4];
     for(String str : strings)
          if(str.length() < counts.length) counts[str.length()] += 1;

     System.out.println(3 + " letter words: " + counts[3]); 

     input.close();

    // TODO Auto-generated method stub

   }//end main

}

它可能看起来像那样,省略循环for(int i = 1; i &lt; counts.length; i++)

【讨论】:

    猜你喜欢
    • 2019-01-27
    • 2019-02-01
    • 2017-09-27
    • 2023-03-22
    • 2012-10-24
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    相关资源
    最近更新 更多