【发布时间】:2017-08-27 16:20:03
【问题描述】:
我目前正在编写一个简单的代码,它将检查用户输入的字符串是否包含在 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);
}
}
如您所见,它会检查字符串是否包含此类字符,并将字符的计数器加一。但是,当我运行它时,我没有收到我预测的结果。 如果我输入GGRY,它会输出1 0 0 0。当期望的输出是
0.5
0.25
0.25
0.0
任何帮助将不胜感激!
【问题讨论】:
-
总计应该等于 4。
-
总的作品,但我遇到了除法部分的问题。