【问题标题】:Get a character from the user and find the no of occurrences of the character in a string given by the user in Java从用户那里获取一个字符,并在 Java 中用户给出的字符串中查找该字符的出现次数
【发布时间】:2021-07-31 10:18:38
【问题描述】:

计算给定字符的出现次数。编写一个程序来接受用户的一句话。从用户那里获取一个字符并找到出现次数。

检查给定的字符和单词是否有效

如果单词仅包含字母且不包含空格或任何特殊字符或数字,则该单词有效。

如果字符是单独的字母,则该字符有效。

示例输入 1: 输入一个词: 编程 输入一个字符: 米

样本输出 1:

No of 'm' present in the given word is 2

示例输入 2: 输入一个词: 编程 输入字符: s

示例输出 2:

The given character 's' not present in the given word.

示例输入 3: 输入一个词: 56 样本输出 3:

Not a valid string

示例输入 4: 输入一个词: 你好 输入字符: 6

示例输出 4:

Given character is not an alphabet

我的代码:

import java.util.Scanner;

public class OccurrenceOfChar {

    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        // Fill the code
        System.out.println("Enter a word:");
        String word=sc.nextLine();
        String words=word.toLowerCase();
        String find="";
        int len=word.length();
        int i, count=0, flag=0;
        for(i=0;i<len;i++)
        {
            char c=words.charAt(i);
            if(!(c>='a' && c<='z'))
            {
                System.out.println("Not a valid string");
                break;
            }
        }
        System.out.println("Enter the character:");
        find=sc.nextLine();
        if(!(find.length()==1) && (find.charAt(0)>='a' && (find.charAt(0)<='z')))
        {
            System.out.println("Given character is not an alphabet");
        }
        for(i=0;i<len;i++)
        {
            if(words.charAt(i)==find.charAt(0))
            {
                count++;
            }
        }
        if(count==0)
            System.out.println("The given character '"+find+"' not present in the given word.");
        else
            System.out.println("No of '"+find+"' present in the given word is "+count);
    }

   }

9 个测试用例中只有 2 个通过。 我无法指出逻辑中的错误。

测试3:检查不存在字符且单词大写时的逻辑

测试 4:检查字符存在且单词大写时的逻辑

测试5:判断单词无效时的逻辑

测试6:检查字符无效时的逻辑

测试7:当字符有2位时检查逻辑

测试8:当单词没有字母时检查逻辑

测试9:检查字符为特殊字符时的逻辑

*注意:所有测试用例的权重可能不同 +------------------------------+ | 9 次测试运行/2 次测试通过 | +------------------------------+

【问题讨论】:

  • 字母大小写重要吗?即字母F被认为在foo中,还是bBar中?
  • @Bohemian 我无法从问题中弄清楚。

标签: java string char


【解决方案1】:

将验证字符串的逻辑移动到单独的方法中,调用此方法来检查给定的单词是否为有效字符串

public boolean validateString(String str) {
      str = str.toLowerCase();
      char[] charArray = str.toCharArray();
      for (int i = 0; i < charArray.length; i++) {
         char ch = charArray[i];
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
        }
      }
      return true;
   }

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 2020-02-26
    • 2017-05-28
    • 2021-12-02
    • 1970-01-01
    • 2014-11-27
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多