[Java原始碼]鍵盤輸入會員卡號,對其格式、位數進行判斷,不符合規則會跳轉重新輸入
阿新 • • 發佈:2019-01-06
4位數的會員卡號,活動期間,4位數字求平均值為5,則商品免費
-----------------------背景-------------------------------分割線---------------------------------------------------
下面一段原始碼包含幾個功能:
1、掃描器宣告,並指定鍵盤輸入
2、對鍵盤輸入的內容,進行格式判斷:只允許輸入數字,否則跳轉重新輸入
3、進行位數判斷,只允許4位,否則跳轉重新輸入
4、對卡號,分割求平均值
原始碼如下:
import java.util.Scanner; /** * 輸入4位會員卡號 * 每位數字相加,然後取平均值,5則中獎 * @author wanglp */ public class DataInput { /** * @param args */ public static void main(String[] args) { /** * 會員卡號,整型型別 */ int icardNo = 0; /** * 會員卡號,字串型別 */ String scardNo = null; /** * 會員卡號第1位數字 */ int no1; /** * 會員卡號第2位數字 */ int no2; /** * 會員卡號第3位數字 */ int no3; /** * 會員卡號第4位數字 */ int no4; /** * 4位數平均值 */ double avg; System.out.print("請輸入您的會員卡號:"); do { /** * 宣告掃描器型別 */ Scanner input = new Scanner(System.in); try { /** * 指定鍵盤輸入,指定字串變數 */ scardNo = input.next(); icardNo = Integer.parseInt(scardNo); } catch (Exception e) { System.out.print("輸入的格式不正確,請重新輸入4位數字:"); continue; } if(scardNo.length()!= 4) { System.out.print("輸入的位數不正確,請重新輸入4位數字:"); continue; }else { break; } }while(true); no4 = icardNo%10; no3 = icardNo/10%10; no2 = icardNo/100%10; no1 = icardNo/1000; avg = (no1 + no2 + no3 + no4)/4; if(avg == 5) { System.out.println("恭喜你!本次免費!"); }else { System.out.println("很遺憾,只能全額支付咯..."); } } }