題目
Math.random()獲取隨機數
Math.random()返回的是一個[0.0,1.0)的doule類型的數
所以,獲取0-9:(int)Math.random()*10–> [0,10)
獲取0-10:(int)Math.random()*10+1–> [0,11)
獲取10-99:(int)Math.random()90+10–> [10,100)
公式:
[a,b]: (int)Math.random()(b-a+1)+a
String類型:使用charAt()獲取字符串的字符
由于要每個數字都進行比較,所以使用String類型并使用charAt(i)獲取第i個位置上字符串的字符
String ticket=scan.next();
//獲取第一和第二個數字
char t1=ticket.charAt(0);
char t2=ticket.charAt(1);
String類型:代碼
import java.util.Scanner;
class PlayTicket {public static void main(String[] args) {
/*
假設你想開發一個玩彩票的游戲,程序隨機地產生一個兩位數的彩票,提示用戶輸入
一個兩位數,然后按照下面的規則判定用戶是否能贏。
如果用戶輸入的數匹配彩票的實際順序,獎金10 000美元。
如果用戶輸入的所有數字匹配彩票的所有數字,但順序不一致,獎金 3 000美元。
如果用戶輸入的一個數字僅滿足順序情況下匹配彩票的一個數字,獎金1 000美元。
如果用戶輸入的一個數字僅滿足非順序情況下匹配彩票的一個數字,獎金500美元。
如果用戶輸入的數字沒有匹配任何一個數字,則彩票作廢。
*///10-99String prize=(int)(Math.random()*90+10)+"";System.out.println("本期獎金號碼為:"+prize);char p1=prize.charAt(0);char p2=prize.charAt(1);Scanner scan=new Scanner(System.in);System.out.println("請輸入彩票號碼:");String ticket=scan.next();//獲取第一和第二個數字char t1=ticket.charAt(0);char t2=ticket.charAt(1);if((t1==p1)&&(t2==p2)){System.out.println("獎金10,000美元");}else if((t1==p2)&&(t2==p1)){System.out.println("獎金3000美元");}else if((t1==p1)||(t2==p2)){System.out.println("獎金1000美元");}else if((t1==p2)||(t2==p1)){System.out.println("獎金500美元");}else{System.out.println("彩票作廢");}}
}
Int類型:獲取兩位數的十位和個位
int ticket=scan.nextInt(); //獲取第一和第二個數字
int t1=ticket/10%10;//十位
int t2=ticket/1%10;//個位
Int類型:代碼
import java.util.Scanner;
class PlayTicket2 {public static void main(String[] args) {//使用int類型//10-99int prize=(int)(Math.random()*90+10);System.out.println("本期獎金號碼為:"+prize);int p1=prize/10%10;//十位int p2=prize/1%10;//個位Scanner scan=new Scanner(System.in);System.out.println("請輸入彩票號碼:");int ticket=scan.nextInt();//獲取第一和第二個數字int t1=ticket/10%10;//十位int t2=ticket/1%10;//個位if((t1==p1)&&(t2==p2)){System.out.println("獎金10,000美元");}else if((t1==p2)&&(t2==p1)){System.out.println("獎金3000美元");}else if((t1==p1)||(t2==p2)){System.out.println("獎金1000美元");}else if((t1==p2)||(t2==p1)){System.out.println("獎金500美元");}else{System.out.println("彩票作廢");}}
}