gpt4 book ai didi

java - 字母计数器(使用子字符串而不是通常的 atChar() 方法)

转载 作者:太空宇宙 更新时间:2023-11-04 14:46:45 25 4
gpt4 key购买 nike

我遇到了编程挑战,并且对于如何让它工作有点困惑。挑战如下:

编写一个程序,要求用户输入字符串,然后要求用户输入字符。程序应该计算并显示指定字符在字符串中出现的次数。

代码:

import java.util.Scanner;
public class F***Around
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
String word, character, test;
int c = 0;

System.out.println("Enter a word: ");
word = keyb.nextLine();

System.out.println("Enter a character: ");
character = keyb.nextLine();

for(int x = 1; x <= word.length(); x++)
{
test = word.substring(1, 2);
if (test.equals(character))
{
c += c;
}
}

System.out.println(c);
}
}

它总是在最后返回 0,我不知道出了什么问题。

最佳答案

需要进行 2 项更改:

  1. 使用迭代变量x来实际循环字符串。目前,您正在对要比较的子字符串进行硬编码,因此循环实际上毫无用处。
  2. c 加 1,因为每找到 1 次字符就会增加计数。

所以,你的代码应该是这样的:

for(int x = 0; x < word.length(); x++)
{
test = word.substring(x, x+1);
if (test.equals(character))
{
c += 1;
}
}

关于java - 字母计数器(使用子字符串而不是通常的 atChar() 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com