【问题标题】:Using strings in Java to accept a password based on certain requirements在 Java 中使用字符串根据某些要求接受密码
【发布时间】:2012-10-01 01:59:20
【问题描述】:

这个程序假设接受输入一个字符串,即密码。然后程序会检查以确保密码长度至少为 8 个字符,至少包含 2 位数字,并且仅包含字母和数字。我似乎无法找到正确的方法来计算至少 2 位数字,尽管据我所知,这种方法应该可以工作。

这是我得到的错误 线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:10 在 java.lang.String.charAt(String.java:658) 在 Password.main(Password.java:35)

import java.util.*;


public class Password{
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    String s;
    int numbers = 0;

    System.out.println("Enter a password (Must contain only letters and numbers, ");
    System.out.print("minimum of 8 characters with atleast two numbers): ");    
    s = input.nextLine();

    while(1==1){
    if (s.length() < 8){
        System.out.println("Password is too short");
        System.out.println("Enter correctly formatted password");
        s = input.nextLine();
        continue;
        }

    if (s.matches("^[a-zA-Z0-9_]+$")){  
    }
    else{
        System.out.println("Password may only contain Letters and Digits");
        System.out.println("Enter correctly formatted password");
        s = input.nextLine();
        continue;
        }



    int i;
    for (i = 0; i <= s.length(); i++){
        if (Character.isDigit(s.charAt(i))){
            numbers++;
            }
            }

    if (numbers < 2){
        System.out.println("Password must contain atleast 2 digits");
        System.out.println("Enter correctly formatted password");
        s = input.nextLine();
        continue;
        }
        break;
        }


    while (0==0){   
    System.out.println("Reenter Password to see if it matches");
        String a = input.nextLine();

    if (s.equals(a)){
        System.out.println("Password matches!");
        break;
        }
    else{
        System.out.println("Password does not match");
        continue;
    }
    }
    }
    }

【问题讨论】:

  • 请注意,while (1 == 1) 可以是while (true)
  • 您是在问如何解决这个问题?还是您在问是什么导致了错误。
  • @A.R.S.或者,只是 while ((s = input.nextLine()).length() &lt; 8),删除了之前的 nextLine。

标签: java string


【解决方案1】:

在你的for循环中,你不应该让i等于s.length()

for (i = 0; i <= s.length(); i++)

ArrayIndexOutOfBoundsException 是在您尝试访问s[s.length()] 时引发的。

【讨论】:

    【解决方案2】:

    由于使用从 0 到长度的索引,此语句正在获取异常。而不是使用 0 到

     for (i = 0; i <= s.length(); i++){
        if (Character.isDigit(s.charAt(i))){
            numbers++;
        }
     }
    

    【讨论】:

      【解决方案3】:

      将 for (i = 0; i

      示例:假设字符串 s = "abc"。 s.length() = 3. s.charAt(0)= "a", s.charAt(1)= "b", s.charAt(2)= "c"。 s.charAt(3) 不存在并抛出异常。

      【讨论】:

        猜你喜欢
        • 2012-03-13
        • 1970-01-01
        • 2014-01-17
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        相关资源
        最近更新 更多