- 計算機隨機產生一個1-100的數位,玩家最多猜5次。每次根據玩家的輸入與亂數比較後提示玩家too hight,too small,bingo
終止條件:
猜中結束
輸入0終止
public static void main(String[] args) {
int number = (int)Math.floor(Math.random()*10);
if(number != 0){
for(int i=0;i<5;){
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("請輸入你要猜的資料(1-100):");
int guessNumber = sc.nextInt();
if(guessNumber==0){
System.out.println("終止!");
break;
}
else if(guessNumber>number){
System.out.println("您猜的數位"+guessNumber+"\ntoo hight"+",您還剩"+(4-i)+"次機會");
i++;
}
else if (guessNumber<number){
System.out.println("您猜的數位"+guessNumber+"\nto small"+",您還剩"+(4-i)+"次機會");
i++;
}else{
System.out.println("bingo!");
break;
}}}}
- 隨機產生[-10,10)之間的小數點後面只有一位的兩個數,使用加、減、乘或除對這兩個數進行一次計算。
結果大於10獲勝,輸出Congratulations!
否則,輸出You lose!
提示:
(1)生成指定範圍的亂數
(2)接收輸入一個運運算元號,輸入不合法運運算元提示使用者重新輸入,如果連續3次輸入不合法運運算元,退出程式,並輸出「Reach the upper limit!!! Good Bye!
public static void main(String[] args) {
DecimalFormat num1 = new DecimalFormat("0.#");
double number = Math.floor(Math.random()*(Math.random() > 0.5 ? 1 : -1)*10);
num1.format(number);
double number2 = Math.floor(Math.random()*(Math.random() > 0.5 ? 1 : -1)*10);
num1.format(number2);
if(number >= -10 | number < 10 & number2 >= -10 | number2 < 10){
for(int i=0;i<3;){
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("請輸入符號(一位運運算元):");
char input = sc.nextLine().charAt(0);
if((number+number2)>10 & input=='+' ){
System.out.println("Congratulations!");
break;
}
else if((number-number2)>10 & input=='-'){
System.out.println("Congratulations!");
break;
}
else if((number*number2)>10 & input=='*'){
System.out.println("Congratulations!");
break;
}
else if((number/number2)>10 & input=='/'){
System.out.println("Congratulations!");
break;
}else if(input!='+'&input!='-'&input!='*'&input!='/'){
System.out.println("重新輸入正確符號!\n"+"您還有"+(2-i)+"次機會");
i++;
}else{
System.out.println("Reach the upper limit!!! Good Bye!");
break;
}}}}