在java中进行字符匹配时出错

时间:2017-11-07 11:07:27

标签: java comparison character

我正在使用下面的代码进行字符比较和检查是否存在某些特殊字符,但它不起作用。知道为什么" ch"与特殊人物的比较不起作用?

Scanner sc= new Scanner(System.in);
System.out.print("Enter the password to validate: ");
String pass = sc.nextLine();    

char ch=0;
for(int i=0;i<pass.length();i++)
{
    ch = pass.charAt(i);

    if(ch !='$' || ch !='@' || ch !='#' || ch !='%' || ch !='&')  
      splchar++;
}

if(splchar == pass.length())
    System.out.println("Invalid Password");
else
    System.out.println("Valid Password");

1 个答案:

答案 0 :(得分:1)

你的情况总是如此

ch !='$' || ch !='@' || ch !='#' || ch !='%' || ch !='&'

是一样的

! (ch == '$' && ch =='@' && ch =='#' && ch =='%' && ch =='&')

由于某个值不能同时为$@,因此该值始终为!(false),然后为true

你想要

ch =='$' || ch =='@' || ch =='#' || ch =='%' || ch =='&'

检查它是否是其中一个角色。

替代 - 数组

您可以使用

简化逻辑
char[] needed = {
    '@', '$', '#', '%', '&'
};

然后您只需在该数组中搜索匹配项,因为Arrays提供了这些方法,您只需要使用Arrays.binarySearch(needed, ch)进行检查,它将返回char的位置匹配或-1没有找到,所以你可以简化

if(Arrays.binarySearch(needed, ch) < 0)  
          splchar++;

Joop Eggen 所说,这需要一个有序的数组才能工作,所以你可以使用

`Arrays.sort(needed)`

当然,搜索字符会变得有点复杂, Joop Eggen 提出了一个适用于char的简化版本:"@$#%&".indexOf(ch) != -1

替代方案 - 正则表达式

您可以使用正则表达式直接将其与String匹配。但我会让你对这个逻辑做一些研究,这是脱离背景的。