【发布时间】: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中,还是b在Bar中? -
@Bohemian 我无法从问题中弄清楚。