【发布时间】:2021-02-02 14:45:04
【问题描述】:
我正在向用户请求一个字符串。在用户输入他们的字符串后,一个提示会询问他们是否想查看字符串中没有、一个或多个空格的字符串,然后显示这些字符串。
我在计算字符串中的空格时遇到了问题。如果字符串中有多个空格,则提供的代码仅计为 1。完整代码:
import java.util.*;
import java.util.Scanner;
public class CountSpacesInStrings {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter anything..., or type QUIT to quit.");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
boolean result = Arrays.stream(array).anyMatch("QUIT"::equals);
if(result)
{
break;
}
}
String str = null;
int len = -1;
System.out.println("Would you like to display strings with No Spaces, One Space or More? Type No, One, More to see the results: ");
String answer = s.nextLine();
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
}
}
}
else if(answer.equals("One"))
{
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
//System.out.print(array[i] + " ");
}
}
}
else
System.out.println("No values to show");
System.out.println();
}
}
我正在查看的部分是:
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
}
}
【问题讨论】:
-
你认为
if (array[i].charAt(i) != ' ') {是做什么的?您只有一个循环可以遍历数组中的所有 sentences,但没有任何机制可以遍历每个句子中的所有 characters。