如何确定用户输入是否有x个字符

时间:2014-02-23 19:12:24

标签: java

尝试制作另一个&&查看lock_combination是否正好是9个字符

import java.util.Scanner;

public class charlespeppers {

    public static void main(String[] args) {

        Scanner user_input = new Scanner (System.in);

        String lock_combination;
        System.out.print ("Please enter a lock combination ( ddRddLddR ) : ");
        lock_combination = user_input.next();


        if (lock_combination.charAt(0) >= '0' && lock_combination.charAt(0)<= '9' 
        &&  lock_combination.charAt(1) >= '0' && lock_combination.charAt(1)<= '9'
        &&  lock_combination.charAt(3) >= '0' && lock_combination.charAt(3)<= '9'
        &&  lock_combination.charAt(4) >= '0' && lock_combination.charAt(4)<= '9'
        &&  lock_combination.charAt(6) >= '0' && lock_combination.charAt(6)<= '9'
        &&  lock_combination.charAt(7) >= '0' && lock_combination.charAt(7)<= '9'
        &&  lock_combination.charAt(2) == 'R'
        &&  lock_combination.charAt(8) == 'R'
        &&  lock_combination.charAt(5) == 'L'
        &&  lock_combination == 9);
        {
            System.out.println("This is a valid lock combination.");
        }

}
}

2 个答案:

答案 0 :(得分:1)

您可以使用String的{​​{3}}方法:

  

public int length() :返回此字符串的长度。长度等于字符串中Unicode代码单元的数量。

if (... && lock_combination.length() == 9)
    System.out.println("This is a valid lock combination.");

答案 1 :(得分:0)

要查找lock_combination的长度,您可以使用以下代码:

if(lock_combination.length() == 9)