有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

计数在我的java代码中,一个简单的计数算法中有一个逻辑错误

因此,在我简单的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. 为什么代码中有两个for循环,它们不是做同样的事情吗


共 (1) 个答案

  1. # 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);
    }
    }