在获取UpperCased之后,为什么程序输出没有单独显示每个字符串?

时间:2016-10-10 20:45:43

标签: java string uppercase

该程序用于将单词的每个首字母转换为UpperCase

public class MainClass {

    public static void main(String[] args) {

        int i;
        String toBeCapped="";

        String str[] ={"This is a ball","This is a bat","this is the wicket"};
        int e=str.length;

        for(int j=0;j<e;j++)
        {
             String[] tokens = str[j].split("\\s");

             for( i = 0; i < tokens.length; i++)
             {
                 char capLetter = Character.toUpperCase(tokens[i].charAt(0));

                 toBeCapped +=  " " + capLetter + tokens[i].substring(1);
            }
            System.out.println(toBeCapped);
        }
    }
}

产生的输出如下: -

This Is The Ball
This Is The Ball This Is The Bat
This Is The Ball This Is The Bat This Is The Wicket

我希望输出为: -

This Is The Ball
This Is The 
This Is The Wicket

请告诉我我犯的错误是什么。谢谢

3 个答案:

答案 0 :(得分:3)

问题是您在打印后永远不会在循环中将""重置为toBeCapped=""

打印结束后在循环结束时添加System.out.println(toBeCapped); toBeCapped=""; // <<== Add this line 将解决此问题:

StringBuilder

请注意,字符串连接在Java中相对昂贵。更好的方法是使用#!/bin/bash sudo echo Starting ... sudo -b MyProcess web services RPC有关此主题的深入讨论。

答案 1 :(得分:0)

以下是有问题的代码。 +=将字符附加到已构建的toBeCapped字符串。您需要在最里面的toBeCapped循环

之后将for字符串设置为空字符串
for( i = 0; i < tokens.length; i++)
{
  char capLetter = Character.toUpperCase(tokens[i].charAt(0));

  toBeCapped +=  " " + capLetter + tokens[i].substring(1);
}
System.out.println(toBeCapped);
}
toBeCapped = "";

答案 2 :(得分:0)

您的代码存在问题,因为toBeCapped变量在循环中使用后永远不会重置。一个好的编码实践是在循环内声明和使用循环变量(不在它之外)

public static void main(String[] args) {
  String str[] ={"This is a ball","This is a bat","this is the wicket"};
  int e = str.length;

  for(int j=0;j<e;j++) {
    String toBeCapped="";
    String[] tokens = str[j].split("\\s");

    for(int i = 0; i < tokens.length; i++) {
      char capLetter = Character.toUpperCase(tokens[i].charAt(0));
      toBeCapped +=  " " + capLetter + tokens[i].substring(1);
    }
    System.out.println(toBeCapped);
  }
}