Java小程序: 找出一个字母在句子中出现几次
比如输入ggotoaparkinGeelong,输出结果就是2(不清楚他这个什么意思,我把题目原文贴出来吧)Writeaprogram,calledFindChar.ja...
比如输入g go to a park in Geelong,输出结果就是2(不清楚他这个什么意思,我把题目原文贴出来吧)Write a program, called FindChar.java to count the number of occurrence of a character in a given sentence. We will run your program with thefollowing command. The inputs are passed to your program through command line arguments.java FindChar character sentenceYour program should treat lower and upper cases equally when searching a character in a sentence. Suppose that your software is given acharacter “g” and a sentence “go to a park in Geelong”. The following is the corresponding command.java FindChar g go to a park in GeelongYour program should print 2 to the console. We will test your program with different characters and sentences.
展开
2个回答
展开全部
import java.util.Scanner;
import java.util.TreeMap;
/**
* 从键盘输入16位长整数,编程统计每个数字出现的个数
* @author young
*
*/
public class CharMapDemo {
// 统计数字或者字符出现的次数
public static TreeMap<Character, Integer> Pross(String str) {
char[] charArray = str.toCharArray();
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
for (int x = 0; x < charArray.length; x++) {
if (!tm.containsKey(charArray[x])) {
tm.put(charArray[x], 1);
} else {
int count = tm.get(charArray[x]) + 1;
tm.put(charArray[x], count);
}
}
return tm;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str = sc.nextLine();
TreeMap<Character, Integer> tm = Pross(str);
System.out.println(tm);
}
}
展开全部
public class FindChar {
public static void main( String []args ){
int num=0;
if ( args.lenth > 0 )
{
char ch=args[0].charAt(0);
for( int i=1;i<args.length;i++ )
{
for( int j=0;j<args[i].length();j++ ) {
if ( ch==args[i].charAt(j) ) num++;
}
}
}
System.out.println(num);
}
}
编译运行:
java FindChar g go to a park in Geelong
public static void main( String []args ){
int num=0;
if ( args.lenth > 0 )
{
char ch=args[0].charAt(0);
for( int i=1;i<args.length;i++ )
{
for( int j=0;j<args[i].length();j++ ) {
if ( ch==args[i].charAt(j) ) num++;
}
}
}
System.out.println(num);
}
}
编译运行:
java FindChar g go to a park in Geelong
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询