java统计指定字符(使用Scanner输入一个字符)的出现次数
问题描述:
import java.util.Scanner;
public class week {
public static void main(String agrs[])
{ String s=new String("hello world");//创建一个字符串
int i,count=0;
i=s.length();
Scanner read=new Scanner(System.in);
String c=read.next();//输 入一个字符
for(i=0;i<=s.length();i++){
String d=s.substring(i,(i+1));
if(d.equals(c))//判断输入字符与每个字符是否相等
count++;
}
System.out.println(count);
}
}
我的代码
答
是字符还是单词?你前面说的是单词
单词的写法
String s=new String("hello world");//创建一个字符串
Scanner read=new Scanner(System.in);
String c=read.nextLine();
int count=0;
for (String s1: s.split(" "))
{
if (c.equals(s1)) count++;
}
System.out.println(count);
答
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
String s=new String("hello world");//创建一个字符串
int i,count=0;
Scanner read=new Scanner(System.in);
String c=read.nextLine().substring(0, 1);//输入一个字符
for(i=0;i<s.length();i++){
String d=s.substring(i,i+1);
if(d.equals(c)) //判断输入字符与每个字符是否相等
count++;
}
System.out.println(count);
}
}