所以我有这个程序应该采取任何用户生成的字符串并显示空白,字母,数字和特殊字符的数量。我不想重复一个问题。这似乎是更具体一些,然后在其他职位谈到。计算用户生成的字符串中的特殊字符
我的错误在于特殊字符。具体的错误是返回0.我引用堆栈溢出已经在他们对此事的每一个讨论。这帮助我形成了特殊的角色方法。
我必须保持的主要方法明确和调用上述方法
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string");
userInput = kbd.nextLine();
countletter(userInput);
countnumber(userInput);
countspecial(userInput);
countSpace(userInput);
}
public static void countletter(String userInput) {
int countletter = 0;
for (int i = 0; i < (userInput.length() - 1); i++) {
char location = userInput.charAt(i);
boolean x = Character.isLetter(location);
if (x) {
countletter++;
}
}
System.out.println("The number of Letters is: " + countletter);
}
public static void countnumber(String userInput) {
int countnumber = 0;
for (int i = 0; i < userInput.length() - 1; i++) {
char location = userInput.charAt(i);
boolean x = Character.isDigit(location);
if (x) {
countnumber++;
}
}
System.out.println("The number of digits is: " + countnumber);
}
public static void countSpace(String userInput) {
int countSpace = 0;
for (int i = 0; i < userInput.length() - 1; i++) {
char location = userInput.charAt(i);
boolean x = Character.isWhitespace(location);
if (x) {
countSpace++;
}
}
System.out.println("The number of white spaces is: " + countSpace);
}
public static void countspecial(String userInput) {
if (userInput == null || userInput.trim().isEmpty()) {
return 0;
}
int countSpecial = 0;
for (int i = 0; i < userInput.length(); i++) {
if (userInput.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial++);
}
}
我在countSpecial初步尝试:
public static void countspecial(String userInput) {
int countSpecial = 0;
for (int i = 0; i < (userInput.length() - 1); i++) {
if (userInput.substring(i, 1).matches("[^A-Za-z0-9]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial++);
}
}
我要去哪里错了,为什么?
最后的增量是一个意外,我道歉。你的解释有助于我的理解。谢谢。 – mbish75
if(userInput == null || userInput.trim()。isEmpty()){ return; 将userInput设置为null之后trim()。isEmpty())实际上是在做什么,我试图理解这行代码。我还没有了解.trim – mbish75
trim()将从字符串中删除前导和尾随空白 –