簡單的舉例以及試用,詳情都寫在注釋裡啦,保證看懂,不懂就問!
import java.util.*;//這個能囊括全部下列能用到的包
public class Guess_the_number {
public static void main(String[] args) {
System.out.println("小老弟,猜價格遊戲開始辣");
Random random = new Random(); //産生随機數
int goods = random.nextInt(100) + 1;
//random産生的是0-99的,是以加一,就可以變成1-100
System.out.println("請輸入100以内的一個猜測價格");
/*Scanner sc = new Scanner(System.in);//特意拉出來的經典輸入方法Scanner
int price = sc.nextInt();
System.out.println(price);*/
int a = 1;
while (a <= 7) { //做7次循環
Scanner sc = new Scanner(System.in);
int price = sc.nextInt();
System.out.println(price);
if (price == goods) {
System.out.println("恭喜你答對了,真正的價格是=" + price);
break; //跳出,這裡有同向對比,continue,return 自行了解啦
} else if (goods < price) {
System.out.println("真的價格更低一些哦");
a++;
} else if (goods > price) {
System.out.println("真的價格更高一些哦");
a++;
}
}
//簡單的循環嵌套while+if/else if
//100以内猜7次,八成能猜中,滿足虛榮心,遊戲通關!
}
}