要点提示:彩票程序涉及产生随机数、比较数字各位,以及运用布尔操作符。
1) 如果用户的输入数匹配彩票的实际顺序,奖金为10 000美元。
2) 如果用户输入的所有数字匹配彩票的所有数字,奖金为3000美元。
3) 如果用户输入的一个数字匹配彩票的一个数字,奖金为1000美元。
注意,两个数字的位中可能是0。如果一个数小于10,我们假设这个数以0开始,从而构建一个两位数。例如,程序中数字8被作为08处理,假设0作为00处理。
下面是一个运算示例:
Enter your lottery pick (two digits): 15
The lottery number is 15
Exact match: you win $100
package Chapter_3;
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int lottery = (int)(Math.random() * 100);
Scanner input = new Scanner(System.in);
System.out.print("Enter your lottery pick(two digits):");
int guess = input.nextInt();
//Get digits from lottery
int lotteryDigist1 = lottery / 10 ;//十位数,舍弃余数
int lotteryDigist2 = lottery % 10;//个位数
//Get digits from guess
int guessDigist1 = guess / 10;
int guessDigist2 = guess % 10;
System.out.println("The lottery number is " + lottery);
if(guess == lottery) {
System.out.println("Exact match: you win $10,000");
}else if(guessDigist1 == lotteryDigist1 && guessDigist2 == lotteryDigist2) {
System.out.println("Match all digits: you win $3,000");
}else if(guessDigist1 == lotteryDigist1
|| guessDigist1 == lotteryDigist2
|| guessDigist2 == lotteryDigist1
|| guessDigist2 == lotteryDigist2) {
System.out.println("Match one digis: you win $1,000");
}else
System.out.println("Sorry,no match");
}
}
输出示例1:
Enter your lottery pick(two digits): 15 The lottery number is 45 Match one digis: you win $1,000
输出示例2:
Enter your lottery pick(two digits):45 The lottery number is 2 Sorry,no match