![](/img/trans.png)
[英]How to get the maximum occurring character and its occurrences from a user inputted String sentence?
[英]Get a character from the user and find the no of occurrences of the character in a string given by the user in Java
计算给定字符的出现次数。 编写一个程序来接受用户的一句话。 从用户那里获取一个字符并找到出现次数。
检查给定的字符和单词是否有效
如果单词仅包含字母且不包含空格或任何特殊字符或数字,则该单词是有效的。
如果字符是单独的字母,则该字符是有效的。
示例输入 1:输入一个单词:编程输入一个字符:m
样品 Output 1:
No of 'm' present in the given word is 2
示例输入 2:输入一个单词:programming 输入字符:s
样品 Output 2:
The given character 's' not present in the given word.
示例输入 3:输入一个单词:56 示例 Output 3:
Not a valid string
示例输入 4:输入单词:Hello 输入字符:6
样品 Output 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:检查字符存在且单词大写时的逻辑
测试五:判断单词无效时的逻辑
测试6:检查字符无效时的逻辑
测试7:检查字符有2位时的逻辑
测试 8:当单词没有字母时检查逻辑
测试9:检查字符为特殊字符时的逻辑
*注意:所有测试用例的权重可能不同 +--------------------------------------------+ | 9 次测试运行/2 次测试通过 | +------------------------------+
将验证字符串的逻辑移动到单独的方法中,调用此方法来检查给定的单词是否为有效字符串
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.