建設網(wǎng)站要注意事項中國最大網(wǎng)站排名
需求:請求程序實現(xiàn)猜數(shù)字小游戲只能試玩三次,如果還想玩,提示:游戲已經(jīng)結束,想玩請充值(www.itcast.cn)
思路:
? ? ? ? 寫一個游戲類,里面有一個猜數(shù)字的小游戲
? ? ? ? 寫一個測試類,測試類中有main()方法,main()方法中按照下面步驟完成
? ? ? ? ? ? ? ? 從文件中讀取數(shù)據(jù)到Properties集合,用load()方法實現(xiàn)
? ? ? ? ? ? ? ? ? ? ? ? 文件已經(jīng)存在:game.txt
? ? ? ? ? ? ? ? ? ? ? ? 里面有一個數(shù)據(jù)值:count=0
? ? ? ? ? ? ? ? 通過Properties集合獲取到玩游戲的次數(shù)
? ? ? ? ? ? ? ? 判斷次數(shù)是否到達三次
? ? ? ? ? ? ? ? ? ? ? ? 如果到了,給出提示:游戲試玩已經(jīng)結束,想玩請充值(www.itcast.cn)
? ? ? ? ? ? ? ? ? ? ? ? 如果不到三次
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 玩游戲
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 次數(shù)+1,重寫寫回文件,用Properties的store()方法實現(xiàn)
package com.aynu13;//游戲類,猜數(shù)字小游戲import java.util.Random;
import java.util.Scanner;public class GuessNumber {private GuessNumber(){}public static void start(){//要完成猜數(shù)字的游戲,首先需要有一個要猜的數(shù)字,使用隨機數(shù)生產(chǎn)該數(shù)字,范圍1到100Random r=new Random();int number = r.nextInt(100)+1;while(true){//程序實現(xiàn)猜數(shù)字,每次均要輸入猜測的數(shù)字值,需要使用鍵盤錄入實現(xiàn)Scanner sc=new Scanner(System.in);System.out.println("請輸入您要猜的數(shù)字:");int guessnumber = sc.nextInt();//比較輸入的數(shù)字與隨機產(chǎn)生的數(shù)字if (guessnumber>number){System.out.println("您猜的數(shù)字"+guessnumber+"大了");} else if (guessnumber<number) {System.out.println("您猜的數(shù)字"+guessnumber+"小了");}else {System.out.println("恭喜你猜對了");break;}}}
}
package com.aynu13;//需求:請求程序實現(xiàn)猜數(shù)字小游戲只能試玩三次,如果還想玩,提示:游戲已經(jīng)結束,想玩請充值(www.itcast.cn)
//
// 思路:
// 寫一個游戲類,里面有一個猜數(shù)字的小游戲
// 寫一個測試類,測試類中有main()方法,main()方法中按照下面步驟完成
// 從文件中讀取數(shù)據(jù)到Properties集合,用load()方法實現(xiàn)
// 文件已經(jīng)存在:game.txt
// 里面有一個數(shù)據(jù)值:count=0
// 通過Properties集合獲取到玩游戲的次數(shù)
// 判斷次數(shù)是否到達三次
// 如果到了,給出提示:游戲試玩已經(jīng)結束,想玩請充值(www.itcast.cn)
// 如果不到三次
// 玩游戲
// 次數(shù)+1,重寫寫回文件,用Properties的store()方法實現(xiàn)import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;public class PropertiesTest {public static void main(String[] args) throws IOException {//從文件中讀取數(shù)據(jù)到Properties集合,用load()方法實現(xiàn)Properties prop=new Properties();FileReader fr=new FileReader("D:\\idea1\\workplace\\myMap\\game.txt");prop.load(fr);fr.close();//通過Properties集合獲取到玩游戲的次數(shù)String count = prop.getProperty("count");int number = Integer.parseInt(count);//判斷次數(shù)是否到達三次if (number>=3){//如果到了,給出提示:游戲試玩已經(jīng)結束,想玩請充值(www.itcast.cn)System.out.println("游戲試玩已經(jīng)結束,想玩請充值(www.itcast.cn)");}else {//玩游戲GuessNumber.start();//次數(shù)+1,重寫寫回文件,用Properties的store()方法實現(xiàn)number++;prop.setProperty("count",String.valueOf(number));FileWriter fw=new FileWriter("D:\\idea1\\workplace\\myMap\\game.txt");prop.store(fw,null);fw.close();}}
}
?
結果為兩種情況如果試玩次數(shù)等于3時顯示:
?小于3時:
?