如何修复我的Java代码以验证变量?

时间:2015-10-26 13:00:11

标签: java char

我目前正在我的计算机科学课上做一个项目,我们假设验证变量的每个字符,看它是否合法。如果它以数字开头则是非法的。如果它以特殊字符开头,那就是合法但不好的风格。如果它有空间,它又是非法的。我现在将发布我当前的代码:

import java.util.Scanner;

public class classOfValidation {

    public static void main(String[] args) {    
        Scanner scan = new Scanner(System.in);    
        String theVariable = null;

        System.out.println("This program checks the validity of variables");    
        System.out.println("Please enter a variable (or press 'q' to quit");

        theVariable = scan.nextLine();

        do {        
            System.out.println("The variable is illegal");    
            theVariable = scan.nextLine();    
        } while (theVariable.startsWith("[0123456789]"));

        do {    
            System.out.println("The variable is illegal");    
            theVariable = scan.nextLine();    
        } while (theVariable.contains("[ ]"));

        do {    
            System.out.println("The variable is legal, but has bad style");    
            theVariable = scan.nextLine();    
        } while (theVariable.startsWith("[!@#$%^&*]"));         
    }    
}

如果你还不能说我是编程新手并且我可能会感到困惑。如果您有任何建议或其他任何您需要我解释的内容,请发表评论。谢谢大家

2 个答案:

答案 0 :(得分:1)

您可以使用单个regex通过String#matches()方法验证您的输入。但是对于您提供的示例,您应该使用while循环,而不是do-while,因为在do while情况下,一旦检查条件,您总是运行它的正文。所以,你最好这样做:

theVariable = scan.nextLine();

while (theVariable.startsWith("[0123456789]")) {
    System.out.println("The variable is illegal");
    theVariable = scan.nextLine();
}

while (theVariable.contains("[ ]")) {
    System.out.println("The variable is illegal");
    theVariable = scan.nextLine();
}

while (theVariable.startsWith("[!@#$%^&*]")) {
    System.out.println("The variable is legal, but has bad style");
    theVariable = scan.nextLine();
}

第二,在您的解决方案中,您正在使用String.startsWith()方法并将一些正则表达式传递给它。请查看javadoc此方法。在那里说:

  

测试此字符串是否以指定的前缀开头。

这意味着,此方法不支持正则表达式,而只是检查字符串是否以传递的字符串开头。所以,你的条件似乎永远不会成真。我不认为,有人会输入[0123456789][!@#$%^&*]

另外,任何条件都会被检查一次,但之后用户可以修改输入,并且不会再次检查预览传递的条件。似乎,在某些条件下,最好与continuebreak进行无限循环,例如:

 //infinit loop, until user enter the `q` or the input is correct
 while (true) {

    //read the input
    theVariable = scan.nextLine();

    //chtck, whether is `quit` command entered
    if ("q".equals(theVariable)) {
        break;
    }

    //if string starts with digit or contains some whitespaces
    //then print alert and let the user to 
    //modify the input in a new iteration
    if (theVariable.matches("^\d+.*|.*\s+.*")) {
        System.out.println("The variable is illegal");
        continue;
    }

    //if string contains some special characters print alert 
    //and let the user to modify the input in a new iteration
    if (theVariable.matches("^[!@#$%^&*].*")) {
        System.out.println("The variable is legal, but has bad style");
        continue;
    }

    //if all the conditions checked, then break the loop
    break;
}

答案 1 :(得分:0)

如果您使用正则表达式,我认为最好的方法。

Here是如何做到这一点的答案。