java - 特殊字符检查,如果语句不起作用。爪哇
问题描述
对于初学者来说,我对java很陌生,所以我不确定是否有更简单的方法来做到这一点。我目前正在创建一个密码检查器。除了我的特殊字符检查外,我的大部分代码都运行顺利。
我的代码检查适用于长度,以及是否有数字,但不适用于我的特殊字符检查。我目前将 if 语句设置为如果字符串中的一个字符不是字母、数字或空格,则设置 specialCharCheck = true。否则,保持为假。
import java.util.Scanner;
public class Project5_Part1 {
public static void main(String[] args) {
String pass;
String confirm;
boolean parameters;
Scanner in = new Scanner(System.in);
System.out.print("Please enter password : ");
pass = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
confirm = in.nextLine();
parameters = isValid(pass);
while (!pass.equals(confirm) || (!parameters))
{
System.out.println("The password is invalid");
System.out.print("Please enter the password again : ");
pass = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
confirm = in.nextLine();
parameters = isValid(pass);
}
if (isValid(pass))
{
System.out.println("The password is valid");
}
}
public static boolean isValid(String pass) {
boolean numberCheck = false;
boolean specialCharCheck = false;
if (pass.length() < 8) {
return false;
} else {
for (int i = 0; i < pass.length(); i++)
{
if(Character.isDigit(pass.charAt(i)))
{
numberCheck = true;
}
if (!Character.isLetterOrDigit(i) && !Character.isSpaceChar(i))
{
specialCharCheck = true;
//System.out.println("Test");
}
else
{
specialCharCheck = false;
}
}
return (numberCheck && specialCharCheck);
}
}
}
我错过了一个简单的错误吗?我知道还有另一种方法可以做到这一点,但我觉得这样做看起来更有效率。这个逻辑对我来说很有意义。
解决方案
Character.isLetterOrDigit(char)需要一个字符作为参数,但您传递的是一个“int i”。你需要有,
if (!Character.isLetterOrDigit(pass.charAt(i)) && !Character.isSpaceChar(pass.charAt(i)))
{
specialCharCheck = true;
//System.out.println("Test");
}
else
{
specialCharCheck = false;
}
推荐阅读
- ionic-framework - 在 Ionic 中成功更新后,MobileFirst 8.0 Direct Update 不更新 UI
- javascript -
返回一个空白页 - ReactJS - android - 在编写 Gradle 依赖项时,我在哪里可以找到要参考的 AndroidX 工件列表?
- json - 如何替换/更新golang中json数组中的键值?
- dart - Onrefresh 指标在条件语句中不起作用
- python - 有人可以帮助解释为什么 python aiohttp 返回的响应内容比 requests.get 多吗?
- database - 使用 laravel 中的现有枚举 col 更改 Column 数据类型
- javascript - 如何合并两个数组对象
- vue.js - 将 Vuex 传递给实例化组件的最佳方式?
- css - 如何设置输入类型选择的下拉菜单?