作者記錄學習面向物件過程中的心路歷程:從聽懂到寫不出來的焦慮,到調試通過時的成就感。本專案實作一個完整的控制台互動程式:註冊 → 登入 → 猜數字抽獎。
package com.azhi.day0824.luck;
import java.util.Scanner;
public class Luck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// ===== 註冊 =====
System.out.println("\n******** 歡迎來到安之抽獎系統 ********\n\n\t首先請您註冊!");
System.out.print("\t請輸入使用者名稱:");
String name = sc.next(); // 暫存,後續未使用
int account = (int) (Math.random() * 9000 + 1000); // 1000-9999
System.out.println("\t為您分配的帳號是:" + account);
System.out.print("\t請輸入密碼:");
String password = sc.next();
System.out.println("\t註冊成功!");
// ===== 登入 =====
System.out.print("\t是否立即登入? y/n :");
String choice = sc.next();
while (choice.equals("y")) {
System.out.print("\t請輸入帳號:");
int inAccount = sc.nextInt();
System.out.print("\t請輸入密碼:");
String inPassword = sc.next();
if (account == inAccount && password.equals(inPassword)) {
System.out.println("\n\t登入成功!");
break;
} else {
System.out.println("\n\t抱歉,帳號與密碼不匹配,請重新輸入");
}
}
// ===== 抽獎 =====
int luckNum = (int) (Math.random() * 100); // 0-99
System.out.print("\n\t親,您要開始抽獎嗎? y/n :");
String play = sc.next();
while (play.equals("y")) {
System.out.print("\t請輸入您猜的數字 0-99:");
int guess = sc.nextInt();
if (guess > luckNum) {
System.out.println("\t您猜大了");
} else if (guess < luckNum) {
System.out.println("\t您猜小了");
} else {
System.out.println("\t恭喜您猜對啦!");
break;
}
}
}
}
******** 歡迎來到安之抽獎系統 ******** 首先請您註冊! 請輸入使用者名稱:小明 為您分配的帳號是:5832 請輸入密碼:123456 註冊成功! 是否立即登入? y/n :y 請輸入帳號:5832 請輸入密碼:123456 登入成功! 親,您要開始抽獎嗎? y/n :y 請輸入您猜的數字 0-99:50 您猜大了 請輸入您猜的數字 0-99:25 您猜小了 請輸入您猜的數字 0-99:37 恭喜您猜對啦!
Math.random() * 範圍 + 起始值nextInt() 後換行符殘留,混用 next() 需注意「有時候什麼都寫不出來,內心焦躁;看著別人一串串寫出來,我卻不知從何入手。但寫出來、調通時,那點成就感最真實。編程確實跟腦子有關,聰明的人一會兒明瞭,我這類『不好使』的,就多花時間、多練、多總結。」—— A_zhi 2016/8/24