每当提示用户输入变量时,都不会检查第一个输入的变量,但之后会检查所有变量。
这是我的代码:
import java.util.*;
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();
while (true) {
theVariable = scan.nextLine();
if ("q".equals(theVariable)) {
System.out.println("Program quitted. Goodbye!");
continue;
}
if (theVariable.matches("^\\d+.*|.*\\s+.*")) {
System.out.println("The variable is illegal");
System.out.println("Please enter a variable (or press 'q' to quit)");
continue;
}
if (theVariable.matches("^[!@#$%^&*].*")) {
System.out.println("The variable is legal, but has bad style");
System.out.println("Please enter a variable (or press 'q' to quit)");
continue;
}
break;
}
System.out.println("The variable is legal and has good style");
scan.close();
}
}
答案 0 :(得分:0)
这是因为你有一行
theVariable = scan.nextLine();
在你的while循环之外。删除该行,你应该是金色的。
答案 1 :(得分:0)
在进行任何检查之前,您要将变量值设置为下一个扫描输入。
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)");
//Here the variable is the value of the first input.
theVariable = scan.nextLine();
//The variable has not been checked but right after the "while (true)" you scan for the next value.
while (true) {
//Here you replace the first value with the second and never check it.
theVariable = scan.nextLine();
//move this to the end of your lool, so the variable gets replace with the next one AFTER the checking code has run on the first one.
if ("q".equals(theVariable)) {
System.out.println("Program quitted. Goodbye!");
continue;
}
if (theVariable.matches("^\\d+.*|.*\\s+.*")) {
System.out.println("The variable is illegal");
System.out.println("Please enter a variable (or press 'q' to quit)");
continue;
}
if (theVariable.matches("^[!@#$%^&*].*")) {
System.out.println("The variable is legal, but has bad style");
System.out.println("Please enter a variable (or press 'q' to quit)");
continue;
//Move it to here, scanning the next variable after the first is checked.
theVariable = scan.nextLine();
}
break;
}
System.out.println("The variable is legal and has good style");
scan.close();
}
}