菜鳥日記—1月17日
案例: 猜猜你的生日號數
寫一個程式,預先想一個1-31的號數,通過五次詢問確定該數并輸出,
import java.util.Scanner;
先準備好所需的字串
public class 猜你的生日號數 {
public static void main(String[] args) {
String set1 =
" 1 3 5 7\n" +
" 9 11 13 15\n" +
" 17 19 21 23\n" +
" 25 27 29 31";
String set2 =
" 2 3 6 7\n" +
" 10 11 14 15\n" +
" 18 19 22 23\n" +
" 26 27 30 31";
String set3 =
" 4 5 6 7\n" +
" 12 13 14 15\n" +
" 20 21 22 23\n" +
" 28 29 30 31";
String set4 =
" 8 9 10 11\n" +
" 12 13 14 15\n" +
" 24 25 26 27\n" +
" 28 29 30 31";
String set5 =
" 16 17 18 19\n" +
" 20 21 22 23\n" +
" 24 25 26 27\n" +
" 28 29 30 31";
//這些數是當它二進制位取一時的值,從倒數第一位到第五位
主程式

//定義變數day用于接收號數的值
int day = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1;i <= 5;i ++){
System.out.println("你的生日號數在這個集合里面嗎?\n");
if (i == 1){
System.out.println(set1);
System.out.println("\n是,請輸入1;不是,請輸入0");
int aaa = sc.nextInt();
day += aaa * 1;
;}
if (i == 2){
System.out.println(set2);
System.out.println("\n是,請輸入1;不是,請輸入0");
int aaa = sc.nextInt();
//這里涉及到位運算和二進制
day += aaa * (1 << 1);
;}
if (i == 3){
System.out.println(set3);
System.out.println("\n是,請輸入1;不是,請輸入0");
int aaa = sc.nextInt();
day += aaa * (1 << 2);
;}
if (i == 4){
System.out.println(set4);
System.out.println("\n是,請輸入1;不是,請輸入0");
int aaa = sc.nextInt();
day += aaa * (1 << 3);
;}
if (i == 5){
System.out.println(set5);
System.out.println("\n是,請輸入1;不是,請輸入0");
int aaa = sc.nextInt();
day += aaa * (1 << 4);
;}
}
System.out.println("\n你的生日號數是:" + day);
}
}
效果圖
假使我們心中想的數是21

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/250214.html
標籤:java
