Java猜數字遊戲
阿新 • • 發佈:2018-11-19
程式碼:
public class Guess{ public static void main(String[] args){ GuessNumber guess = new GuessNumber(); java.util.Random random = new java.util.Random(); final int value =random.nextInt(100); guess.guessNumber(value); } } class GuessNumber{ //生成隨機數value public void guessNumber(int value){ int count = 0; java.util.Scanner scanner = new java.util.Scanner(System.in); while(true){ System.out.println("請輸入一個數字:"); int num = scanner.nextInt(); if(num>value){ System.out.println("您輸入的數字大了"); }else if(num<value){ System.out.println("您輸入的數字小了"); }else{ System.out.println("恭喜你猜對了"); break; } count++; } System.out.println("您猜了"+count+"次"); } }
執行結果: