【问题标题】:Java String Array, count number of spaces " " [duplicate]Java字符串数组,计算空格数“” [重复]
【发布时间】: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

标签: java arrays count


【解决方案1】:

根据@Pshemo 的评论:您需要添加一个嵌套的 for 循环。第二个 for 循环必须遍历 array[i] 的内容(构成一个句子)并计算该句子中 ' ' 的字符数。

【讨论】:

  • 这不是问题。请注意,循环 for (int i = 0; i &lt; array.length;i++) { 迭代数组中的元素,因此为该数组中的每个元素设置 count0 是正确的。 OP 现在需要检查每个句子中的所有字符。
  • @Pshemo 对,我错过了那部分逻辑。感谢您的澄清!
猜你喜欢
  • 2014-07-04
  • 2014-05-16
  • 2017-09-03
  • 2020-08-17
  • 1970-01-01
  • 2016-06-04
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多