[英]Java Exception Handling (Empty spaces in user input)
我需要創建一個異常類,當用戶輸入的名稱,密碼等(所有字符串)中有空格時,該異常類將引發異常。 我已經寫了所有我認為必要的代碼,無論輸入什么,總是會拋出異常。
我究竟做錯了什么?
以下是代碼片段。 如果需要整個程序,請告訴我。
EmptyInputException
類:
public class EmptyInputException extends Exception{
public EmptyInputException(){
super("ERROR: Spaces entered - try again.");
}
public EmptyInputException(String npr){
super("ERROR: Spaces entered for " + npr + " - Please try again.");
}
}
這是我捕獲異常的getInput
方法:
public void getInput() {
boolean keepGoing = true;
System.out.print("Enter Name: ");
while (keepGoing) {
if(name.equalsIgnoreCase("Admin")){
System.exit(1);
}else
try {
name = scanner.next();
keepGoing = false;
throw new EmptyInputException();
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}//end loop
}
System.out.print("Enter Room No.:");
while (keepGoing) {
if(room.equalsIgnoreCase("X123")){
System.exit(1);
}else
try {
room = scanner.next();
if (room.contains(" ")){
throw new EmptyInputException();
}else
keepGoing = false;
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}
System.out.print("Enter Password:");
while (keepGoing) {
if(pwd.equals("$maTrix%TwO$")){
System.exit(1);
}else
try {
pwd = scanner.next();
keepGoing = false;
throw new EmptyInputException();
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}
}
我感覺好像丟失了掃描儀輸入中應該包含空格的部分,例如:
if(name.contains(" "))
等等...
到目前為止,我的輸出(例如,輸入名稱后)將顯示Error: Please do not put spaces.
try {
name = scanner.next();
keepGoing = false;
if(name.contains(" "))
throw new EmptyInputException();
}
應該做到這一點嗎?
你的猜測是對的。
try {
name = scanner.next();
keepGoing = false;
throw new EmptyInputException(); // You're always going to throw an Exception here.
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
可能是粗心的錯誤。 需要一個if(name.contains(" "))
:D您的密碼塊發生了同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.