我想检查 astring
是否有 8 个或更多字符,以及它是否有 1 个大写字母和 1 个数字。
这是我的代码:
import java.util.Scanner;
public class PasswordTest
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
System.out.printf("Enter a password to be checked: \n");
String passwordInput = keyb.next();
int numberCharaters = passwordInput.length();
int numberCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
int numberNumbers = numberCount - 1;
int captialCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = 'A'; c <= 'Z'; c++)
{
if (passwordInput.charAt(i) == c)
{
captialCount++;
}
}
}
int numberCaptials = captialCount - 1;
if (numberCharaters >= 8 && numberNumbers >= 1 && numberCaptials >= 1)
{
String strongEnough = "Password is strong enough.";
System.out.println(strongEnough);
}
else
{
String strongEnough = "Password is not strong enough.";
System.out.println(strongEnough);
}
}
}
这是我收到的错误信息
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at passwordtest.main(passwordtest.java:23)
我的输入是: Test1
我究竟做错了什么?我一直在试图弄清楚java.lang.StringIndexOutOfBoundsException:
它来自哪里。
你的程序有一些错误。
您应该初始化numberCount
为0
以避免以后必须减去,并避免必须创建另一个变量。此外,您遇到的错误是因为<=
,因为没有字符串 element =到字符串的长度,即索引从 0 到 length - 1。
int numberCount = 0;
for (int i = 0; i < numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
然后,对于capital count
你犯了同样的错误,我也会考虑评论中的建议来改进循环。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句