1. 程式人生 > >JavaSE8基礎 要求輸入給定的字符串,只有三次機會

JavaSE8基礎 要求輸入給定的字符串,只有三次機會

結構 import input system.in brush key lease java源碼 equals



os :windows7 x64
jdk:jdk-8u131-windows-x64
ide:Eclipse Oxygen Release (4.7.0)


code:

package jizuiku.t02;

import java.util.Scanner;

public class Demo04 {
	public static void main(String[] args) {
		String keyWord = "jizuiku";
		String userInput = "";
		Scanner sc = new Scanner(System.in);

		int count = 3;// 有三次輸入的機會
		System.out.println("請輸入 jizuiku");

		// 因為用戶至少會輸入一次數據,所以采用do-while結構
		do {
			// 程序提示上的優化
			if (count == 3) {
				System.out.println("你有" + count + "次機會進行輸入");
			} else {
				System.out.println("還有" + count + "次機會");
			}

			// 接收用戶的輸入
			userInput = sc.nextLine();

			// 對用戶的輸入進行判斷
			if (userInput.equals(keyWord)) {
				System.out.println("輸入正確");
				break;
			} else {
				System.out.println("輸入錯誤");
			}

		} while ((--count) != 0);//先進行count--,然後在不等於0的話進行開始下一輪
		
		sc.close();
		System.out.println("程序結束");
	}
}


result_1:

技術分享

result_2:
技術分享


Java優秀,值得學習。
學習資源:API手冊+Java源碼。

JavaSE8基礎 要求輸入給定的字符串,只有三次機會