1
只要它提示用戶輸入變量,第一個輸入的變量就不會被檢查,但所有變量都會被檢查。驗證項目 - 程序不接受來自用戶的第一個輸入
這裏是我的代碼:
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("^[[email protected]#$%^&*].*")) {
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();
}
}
你調用'theVariable = scan.nextLine();'while循環之前,和immidiatly再次調用它作爲循環中的第一個語句。我猜這就是你的「不檢查」應該是什麼意思。 – SomeJavaGuy
固定!謝謝,應該刪除這篇文章 – TheNewYo
使用next(),nextInt()或其他nextFoo()方法之後跳過nextLine()的可能的副本(http://stackoverflow.com/questions/13102045/skipping-nextline-after - 使用 - 下一nextint - 或其它-nextfoo的方法) – Raf