Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:如何计算字符串中的字符数_Java - Fatal编程技术网

Java:如何计算字符串中的字符数

Java:如何计算字符串中的字符数,java,Java,我必须计算一个字符在字符串中出现的次数 我知道以前有人问过这个问题。然而,我看到的解决方案使用了我在课堂上还没有介绍的命令/技术 这是我的密码: import java.util.Scanner; /* This program counts the number of occourances of a char in a string. */ public class LetterCounter { public static void main(String[] args) { int

我必须计算一个字符在字符串中出现的次数

我知道以前有人问过这个问题。然而,我看到的解决方案使用了我在课堂上还没有介绍的命令/技术

这是我的密码:

import java.util.Scanner;
/*
This program counts the number of occourances of a char in a string.
*/

public class LetterCounter
{
public static void main(String[] args) 
{
int i, length, count=0;
String input;
char letter1, letter2;

// Create a Scanner object for keyboard input.
Scanner stdin = new Scanner(System.in);

// Get a string from user
System.out.print("Enter a string: ");
input = stdin.nextLine();

// Get a character from user 
System.out.print("Enter a character: ");
letter1 = stdin.next().charAt(0);

//Determine the length of the string
length = input.length();

//Count the number of times the user selected character appears in the string
for (i = 0; i <= length; i++) 
{
    letter2 = input.charAt(i);
    if (letter1 == letter2)
{
count++;
}
}

System.out.printf("Occurrences of a %s in %s is %d", letter1, input, count);      
import java.util.Scanner;
/*
这个程序计算字符串中字符的occourance数。
*/
公营信笺台
{
公共静态void main(字符串[]args)
{
int i,长度,计数=0;
字符串输入;
字符字母1,字母2;
//为键盘输入创建扫描仪对象。
扫描仪标准输入=新扫描仪(System.in);
//从用户获取字符串
System.out.print(“输入字符串:”);
输入=stdin.nextLine();
//从用户处获取字符
System.out.print(“输入字符:”);
字母1=标准的下一个字符(0);
//确定字符串的长度
长度=输入。长度();
//计算用户选择的字符在字符串中出现的次数

对于(i=0;i错误发生在下面的代码行中-

for (i = 0; i <= length; i++) 

(i=0;i的
看起来您只是重复了太长时间:

for (int i = 0; i <= length; i++) {
    ...
}
我会避免使用count++,你可能会在某个时候和它混在一起

if (letter1 == letter2) {
    count + =1;
}

请尝试
i
而不是
i,这一异常非常明显。您认为字符串索引超出范围可能意味着什么,特别是当它后面跟着字符串索引超出范围时:11引用了
string.charAt()
?您在哪里看到
string.charAt()
在您发布的代码中?是什么原因导致它抛出字符串索引超出范围的异常?
for (int i = 0; i < length; i++) {
    ...
}
if (letter1 == letter2)
{
    count++
}
if (letter1 == letter2) {
    count + =1;
}