检查字符串是否包含带for for循环的字符?

Gla*_*ace 2 java string for-loop char

我目前正在研究一个简单的代码,它将检查用户输入的String是否包含for循环中指定的字符.

我目前的代码

import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int G = 0;
    int R = 0;
    int Y = 0;
    int B = 0;
    String S = sc.nextLine();
    for (int i = 0; i < S.length(); i++) {
        if (S.contains("G")) {
            G++;
        } else {
            if (S.contains("R")) {
                R++;
            } else {
                if (S.contains("Y")) {
                    Y++;
                } else {
                    if (S.contains("B")) {
                        B++;
                    }
                }
            }
        }
    }
    int total = G + R + Y + B;
    System.out.println(G/total);
    System.out.println(R/total);
    System.out.println(Y/total);
    System.out.println(B/total);
}
Run Code Online (Sandbox Code Playgroud)

}

如您所见,它检查字符串是否包含此类字符,并将字符的计数器增加一.但是,当我运行它时,我没有收到我预测的结果.如果我输入GGRY,它输出1 0 0 0.当所需的输出为

0.5 0.25 0.25 0.0

任何帮助,将不胜感激!

Leo*_*eon 6

问题是S.contains如果整个字符串包含给定的字符,则返回true.S.charAt应该解决你的问题:

for (int i = 0; i < S.length(); i++) {
    if (S.charAt(i) == 'G') G++;
    else if (S.charAt(i) == 'R') R++;
    else if (S.charAt(i) == 'Y') Y++;
    else if (S.charAt(i) == 'B') B++;
}
Run Code Online (Sandbox Code Playgroud)

此外,除以整数将返回一个整数(向下舍入).因此,0除非所有字符都相同,否则您的输出将始终如此.double在打印之前将它们转换为:

System.out.println((double) G/total);
System.out.println((double) R/total);
System.out.println((double) Y/total);
System.out.println((double) B/total);
Run Code Online (Sandbox Code Playgroud)

编辑:正如Sumit Gulati在评论中指出的那样,switch语句将在Java 7中具有更好的性能.另外,正如David Conrad所指出if的,在for循环中仅使用s 也会起作用,因为条件是互斥的.

  • (由于条件相互排斥,因此不严格需要'else`.) (2认同)