java - 使用 for 循环创建仅包含数字和数字的密码
问题描述
我正在制作一个程序,该程序从用户那里获取一个字符串来创建密码。但是,此密码至少需要 8 个字符或更多,并且只能包含字母(大写和小写)和数字。我已经这样做了,但是,当我在用户输入一个空格(例如:“密码”)或特殊符号(如“%”或“&”)时,该方法仍然返回值 true,使密码当它不应该返回这个时有效,我该如何纠正这个?
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
System.out.println("Enter your password");
Scanner input = new Scanner(System.in);
String pass = input.nextLine();
System.out.println("Is the password valid? " + passwordCheck(pass));
}
public static boolean passwordCheck(String password)
{
boolean pass = false;
for(int i=0; i < password.length(); i++)
{
char c = password.charAt(i);
if(password.length() >= 8)
{
if(c >= 48 && c <= 57)
{
pass = true;
}
else if(c>= 97 && c<= 122)
{
pass = true;
}
else if(c>=65 && c<=90)
{
pass = true;
}
else if(c == 32)
{
pass = false;
}
}
}
return pass;
}
}
解决方案
一旦遇到空格或任何其他特殊字符,您就需要跳出循环。
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
System.out.println("Enter your password");
Scanner input = new Scanner(System.in);
String pass = input.nextLine();
System.out.println("Is the password valid? " + passwordCheck(pass));
}
public static boolean passwordCheck(String password)
{
boolean pass = false;
for(int i=0; i < password.length(); i++)
{
char c = password.charAt(i);
if(password.length() >= 8)
{
// also you can directly mention the character instead of looking for its respective ASCII value
if(c >= '0' && c <= '9')
{
pass = true;
}
else if(c>= 'a' && c<= 'z')
{
pass = true;
}
else if(c>='A' && c<='Z')
{
pass = true;
}
else // loop will break if it encounters a space or any other
special character
{
pass = false;
break;
}
}
}
return pass;
}
}
推荐阅读
- mysql - 带有表达式的Mysql复合索引不起作用
- javascript - 如何从本地存储反应中获取价值
- java - 如何在两个数据集选项(如 DB)之间使用类似的减法来设计 Redis 搜索/扫描算法
- r - R创建笔记本时出错:剪贴板模式
- kotlin - 版本控制插件。插件的BOM?
- javascript - 在 react-widgets 组合框中过滤:完全匹配显示整个列表而不是匹配项
- php - 有没有办法在主页内容中显示使用 php curl 检索到的图像
- javascript - 如何将数据从 Firestore 导入 Vue CLI 项目?
- c++ - 而不是这么多 if 语句,我想要一个逻辑,我可以用一个语句或优化的方式来做到这一点
- javascript - 如何模拟 navigation.useragent