我想要計算字符串中非空白字符的數量。使用字符串方法來計數字符
當沒有前導空格時它工作正常,但當我從中添加3個空格時,它會使非空白字符的數量加倍。
這是我的代碼:
import java.io.*;
import java.util.*;
public class countCharacters
{
public static void main(String[] args) throws Exception
{
String str1;
int count;
count = 0;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
while(str1.length() > 0)
{
System.out.println("The String ''" + str1 + "''");
System.out.println("has " + str1.length() + " Characters, including all blanks.");
for(int i=0; i < str1.length(); ++i)
if(str1.charAt(i) !=' ')
count++;
str1 = str1.trim();
System.out.println("and " + str1.length() + " Characters, trimmed of leading and trailing blanks.");
System.out.println("and " + count + " non-blank characters.");
System.out.println("");
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
}
System.out.println("Program complete.");
}
}
相信我 - 格式化您的代碼將有助於您在調試過程中很多。如果你看不懂它,你怎麼能檢查你的代碼!如果您使用的是Eclipse,請按Ctrl + Shift + f,並且您的代碼將自動生成。在這一點上我真的不能看你的代碼,因爲它對我來說是不可讀的。 – 2014-11-04 18:30:09
如果在**數字之前修剪**,會不會更好? – 2014-11-04 18:30:55
@MatiCicero他/她只是在執行'trim'以輸出字符串的修剪長度。這些角色已經被計算在內。無論它們是在「trim」之前還是之後都被計算在內。 – 2014-11-04 18:31:31