我的Java代码中的简单计数算法中存在逻辑错误

时间:2019-03-24 10:57:34

标签: java count

所以我的简单Java计数单词内部存在逻辑错误,首先是在cmd中,它要求我两次键入字符串,何时应显示一次

我在cmd中运行它,这是输出:

C:\Users\Me\Documents>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2
import java.util.Scanner;
public class count5 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();

        char key = input.nextLine().charAt(0);
        countString(str, key);
    }

    public static void countString(String str, char key) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == key)
                count++;
        }
        System.out.println("Number of Occurrence of "
                + key + " is " + count + " in string " + str);

        for (int i = 0; i < count; i++) {
            System.out.println(key);
        }

        if (count > 0) {
            System.out.println(count);
        }
    }
}

所以这让我有些困惑:

  1. 为什么需要3行以允许用户键入输入。我以为上一行已经允许我输入输入。 char key = input.nextLine().charAt(0);需要什么,以及上一行?

  2. 为什么在代码内有2个for循环,它们不做相同的事情吗?

1 个答案:

答案 0 :(得分:1)

尝试此解决方案,该解决方案应要求一次输入并遍历为比赛输入的完整输入字符串

import java.util.Scanner;  

public class stringCompair {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String str = input.nextLine();
    for(int i=0 ; i < str.length();i++) {
        char key = str.charAt(i);
        countString(str, key);
    }

}

public static void countString(String str, char key) {
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == key)
            count++;
    }
    System.out.println("Number of Occurrence of "
            + key + " is " + count + " in string " + str);
}
}