【发布时间】:2015-10-26 13:00:10
【问题描述】:
我目前正在我的计算机科学课上做一个项目,我们假设验证变量的 每个 字符以查看它是否合法。如果它以数字开头,那是非法的。如果它以特殊字符开头,则它是合法的,但样式不好。如果它有一个空间,它又是非法的。我现在将发布我当前的代码:
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("[!@#$%^&*]"));
}
}
如果您还不能告诉我我是编程新手并且可能会感到困惑。如果您有任何建议或其他需要我解释的内容,请发表评论。谢谢大家
【问题讨论】:
-
如果你第一次输入像“asdbasdb”这样的变量,程序会跳过第一个而输入第二个,让我使用“1234”作为变量名而不说它是错误的。您应该将代码放入一个 while(或 do...while)循环中,并使用 if 语句检查不同方面,只记住在当前循环运行期间这些 if 之一是否为真(像“isValidName”这样的布尔变量可以在这里帮助)。