這是一個簡單的遊戲本來作者讓電腦出題 玩家猜

我加入了 讓玩家出題 電腦猜的功能

============================

猜數字  

============================

import java.io.*;
import java.util.Scanner;
public class pxt {
static Scanner sr = new Scanner(System.in);
 public static void main(String[] args){
pxt p=new pxt(); 
    System.out.println("~~~猜數字~~~,你要猜請按1,讓電腦猜請按2");
    int item=sr.nextInt();//放讓使用者輸入的值
    switch(item){
       case 1://如果是1
      p.guess1();//呼叫guess1函式
      break;
       case 2://如果是2
      p.guess2();//呼叫guess2函式
      break;
       default://否則結束程式
      break;   
    }
 }
  public void guess1(){
  int s = 1,i = (int)(Math.random()*100)+1;//宣告變數,並產生電腦的亂數
  System.out.println("範圍1~100");
  while (i>0) {//這邊使用while迴圈
  System.out.println("請輸入你猜的:");
  int guess = sr.nextInt();//玩家輸入自己猜的數字
  if(guess < i){
  System.out.println("再大一點唷!這是第"+s+"次");//if判斷猜對或猜錯,猜錯將會產生提示
  s++;
  }
  else if (guess > i){
  System.out.println("再小一點唷!這是第"+s+"次");
  s++;
  }
  else{
  System.out.println("你總共猜了"+s+"次!");
  break;}//猜對了,所以使用break跳出迴圈
  }
  System.out.println("恭喜你猜對了!");  
  }
  public void guess2(){//讓電腦猜
  System.out.println("輸入一個數字1-100");//請使用者輸入一個1-100的數字
  int an=sr.nextInt();
  int guess;
  while(1<2){//除非猜對否則會一直跑
  guess=(int)(Math.random()*100)+1;//電腦會隨機猜一個數字
  System.out.println("電腦猜:"+guess);
  if(guess==an){//如果猜中顯示電腦猜對了然後離開城程式
  System.out.println("電腦猜對了!!!");
  break;
  }else{//如果沒猜中顯示電腦沒猜中 然後繼續跑while迴圈猜
  System.out.println("電腦沒猜中!!!");
  }
  }
  }
}


arrow
arrow
    全站熱搜

    cookiesp 發表在 痞客邦 留言(0) 人氣()