我正在为学校的一个班级开发一个程序,它要求我们编写一个Java程序来从用户那里获取一个String,然后打印出大写字母,小写字母和空格的数量。代码工作正常,问题在于,它重复两次相同的输出。
代码:
String isUp = "";
String isLo = "";
int spaceCount;
System.out.print("Please give a string: ");
String x = input.nextLine();
int z = x.length();
for(int y = 0; y < z; y++){
if (Character.isUpperCase(x.charAt(y))){
char u = x.charAt(y);
isUp = isUp + u + " ";
}
if (Character.isLowerCase(x.charAt(y))){
char v = x.charAt(y);
isLo = isLo + v + " ";
}
spaceCount = 0;
for (char c : x.toCharArray()) {
if (c == ' ') {
spaceCount++;
}
}
System.out.println("The uppercase characters are " + isUp);
System.out.println("The lowercase characters are " + isLo);
System.out.println("The number of whitespaces is " + spaceCount);
}
我得到的输出是:(使用的字符串:“Stack Overflow”)
我怎样才能做到这一点我只得到一个输出?感谢帮助,如果我错过了Java API上的某些内容,请随时告诉我! (没有downvotes)谢谢!
答案 0 :(得分:3)
您的println
语句在for
循环内。将它们移到for
循环之外。
此外,您必须在声明时初始化spaceCount
变量。
答案 1 :(得分:1)
除了B.Naeem的答案之外,你的循环可以简化为类似的东西。
for(int y = 0; y < z; y++){
if (Character.isUpperCase(x.charAt(y))){
char u = x.charAt(y);
isUp = isUp + u + " ";
} else if (Character.isLowerCase(x.charAt(y))){
char v = x.charAt(y);
isLo = isLo + v + " ";
} else if (Character.isWhitespace(x.charAt(y))) {
spaceCount++;
}
}
基本上或者这样做是检查角色是上部套管还是下部套管还是空间,就像它们中的任何一个一样,它不能是另一个
答案 2 :(得分:0)
将您的打印语句移到for
循环之外。另外,从循环中删除spaceCount = 0;
。相反,请将int spaceCount;
替换为int spaceCount = 0;
。