我寫了一些代碼來檢查用戶是否輸入了1到5之間的數字,現在我還想讓我的代碼允許用戶輸入字母A,S,D或M.if if else語句的多個變量
有沒有一種方法可以組合代碼,我可以識別用戶是否輸入了1-5或A,S,D,M?
如何編輯下面的代碼,以便用戶可以輸入整數或字符?我是否必須在循環下面編寫一段代碼,以確定用戶沒有輸入1-5,但是輸入A,S,D或M,就像跳出循環一樣?或者它是一個獨立的循環。我感到很困惑!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Selection {
Scanner readInput = new Scanner(System.in);
int selectionOne() {
int inputInt;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for subtraction, M for multiplication, or D for division: ");
try {
inputInt = readInput.nextInt(); //user will enter a response
if (inputInt >= 1 && inputInt <=5) {
System.out.print("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have not entered the correct number, please try again.");
}
continue;
}
catch (final InputMismatchException e) {
System.out.println("You have entered an invalid choice. Try again.");
readInput.nextLine(); // discard non-int input
continue; // loop will continue until correct answer is found
}
} while (true);
return inputInt;
}
}
如果你的輸入可以是字母,但您可以在定義輸入字段作爲一個int,你猜什麼事情發生?你期望你的用戶輸入一個ASCII碼嗎?提示:字符串+解析。 – MarsAtomic 2014-11-03 22:28:31
我對此很新,你能否進一步解釋如何將字符串加入到這個中?謝謝 – userQuestion 2014-11-03 22:46:06
有沒有任何答案對您有幫助? – 2014-11-04 00:11:51