大家好,我现在有一个程序应该只计算白色空间,但我的程序似乎在计算所有可以有人识别丢失或错误的位置?
public class SpaceCounter {
public static void main(String[] args) {
Scanner scan = new Scanner(SpaceCounter.class.getResourceAsStream("Test")) .useDelimiter("\\s"); // imports the text file and uses delimiter to count the spaces
int counter1 = 0; //sets 1st counter 1
while (scan.hasNextLine()) { // while loop
scan.next(); // scanner goes onto next line
counter1++;
}
System.out.println("this file contains this amount of spaces: " + counter1);
}
}
答案 0 :(得分:1)
int spaceCount = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
spaceCount++;
}
}
你可以像这样实现它
答案 1 :(得分:0)
更改你的while循环和代码,如下所示:
while (scan.hasNextLine()){ // while loop
String s= scan.next(); // scanner goes onto next line
counter1 += s.length() - s.replaceAll(" ", "").length();
}
答案 2 :(得分:0)
如果你想计算文本中的空格数量,并且真的想要使用Scanner
,你可以使用这样的东西:
public class SpaceCounter {
public static void main(String[] args) {
Scanner scan = new Scanner(SpaceCounter.class.getResourceAsStream("Test")).useDelimiter("\\S*");
int counter1 = 0;
while (scan.hasNext()) {
scan.next();
counter1++;
}
System.out.println("this file contains this amount of spaces: " + counter1);
}
}
答案 3 :(得分:0)
我宁愿使用类似的东西:
// FIRST OF ALL: Delete the .useDelimiter("\\s") from your Scanner
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.isEmpty()) {
counter1++;
} else {
for (int i = 0; i < line.length(); i++) {
if (Character.isWhitespace(line.charAt(i))) {
counter1++;
}
}
}
}