gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:50:59 26 4
gpt4 key购买 nike

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

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("[!@#$%^&*]"));
}
}

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

最佳答案

您可以使用单个 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 来了解此方法。那里说:

Tests if this string starts with the specified prefix.

这意味着,此方法不支持正则表达式,而只是检查字符串是否以传递的字符串开头。所以,你的条件似乎永远不会成为现实。我不认为有人会输入 [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;
}

关于java - 如何修复我的 Java 代码以验证变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33346420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com