java實驗之猜數遊戲

來源:互聯網
上載者:User

標籤:inpu   程式   main   string   結束   scanner   參數   退出   ring   

 猜數遊戲,要求:

(1)編寫一個方法用於產生1-1000之間的隨機數;

(2)編寫一個方法用於完成兩個數的比較,參數(隨機數,使用者提供的數字),傳回值:

>0 使用者提供的數字比隨機數大

=0 使用者提供的數字跟隨機數一樣大

<0 使用者提供的數字比隨機數小

(3)編寫一個測試方法,為使用者提供猜數字遊戲過程。

程式擴充一:每次猜數結果如果不對,則提示猜大了還是猜小了,最多可以猜10次。

程式擴充二:一次猜數結束,可以讓使用者選擇是繼續下一輪遊戲還是退出。

package random;
import java.util.Scanner;
import java.util.Random;
public class l {
public static void main(String args[]){
int random,fate,z1,z2;
random=random();
for(int i=1;i<=10;i++){
System.out.println("請輸入一個數(1~1000):");
fate=getInput();
z1=compare(random,fate);
display(z1);
if(z1==0)
break;
if(i==10){
System.out.println("機會已用盡!");
break;
}
if(i<10)
System.out.println("還剩"+(10-i)+"次機會!");
if(i<10){
System.out.println("輸入0退出,輸入其它數繼續!");
z2=getInput();
if(z2==0)
break;
}
}

}
public static int random(){ //產生隨機數
int max=1001;
int min=1;
Random random=new Random();
int sr=random.nextInt(max)%(max-min+1) + min;
return sr;
}
public static int getInput(){ //輸入資料
Scanner scan=new Scanner(System.in);
int ss=0;
ss=scan.nextInt();
return ss;
}

public static int compare(int i,int j){ //比較大小
if(i<j)
return 1;
else if(i==j)
return 0;
else
return -1;
}
public static void display(int i ){ //顯示結果
switch(i){
case 1:System.out.print("數字偏大!");break;
case 0:System.out.print("恭喜你猜對了!");break;
case -1:System.out.print("數字偏小!");break;
}
}
}

java實驗之猜數遊戲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.