可能重复:
JAVA:检查字符串中是否有特殊字符
我是一名初学者程序员,正在寻求帮助确定一个字符是否为特殊字符。我的程序要求用户输入文件名,然后读取文件中的文本,并确定文本中有多少个空格、数字、字母和特殊字符。我已经完成了用于确定空格、数字和字母的代码,但是不确定如何检查一个字符是否为特殊字符。如果您能提供任何帮助,我将不胜感激,如果有什么不清楚的地方,我可以尝试说明。我目前的代码如下:
import java.util.Scanner;
import java.io.*;
public class TextFile{
public static void main(String[] args){
Scanner input = new Scanner (System.in);
String fileName;
boolean goodName = false;
int blankCount = 0;
int letterCount = 0;
int digitCount = 0;
int specialcharCount = 0;
String currentLine;
char c;
Scanner lineFile= null;
FileReader infile;
System.out.println("Please enter the name of the file: ");
fileName = input.nextLine();
while (!goodName) {
try{
infile = new FileReader(fileName);
lineFile = new Scanner(infile);
goodName= true;
}
catch(IOException e) {
System.out.println("Invalid file name, please enter correct file name: ");
fileName=input.nextLine();
}
}
while (lineFile.hasNextLine()){
currentLine = lineFile.nextLine();
for(int j=0; j<currentLine.length();j++){
c=currentLine.charAt(j);
if(c== ' ') blankCount++;
if(Character.isDigit(c)) digitCount++;
if(Character.isLetter(c)) letterCount++;
if() specialcharCount++;
}
}
}
}
我需要在最后的if语句中放置一些东西来增加specialcharCount。
else specialCharCount++
就可以实现。 - Anthony Acciolyif(Character.isDigit(c))
和if(Character.isLetter(c))
替换为else if(Character.isDigit(c))
和else if(Character.isLetter(c))
,这样只有当字符不是空格、数字或字母时才会进入else
语句。 - Anthony Accioly