程序代码:
import java.util.*;
public class Questions {
Scanner reader = new Scanner(System.in);
public int get(int num, int index) {
if(num < 0 || index < 0 || index > (int)Math.log10(num))
return - 1;
int i = (int)Math.ceil(Math.pow(10, index));
return num / i % 10;
}
public Questions question1() {
System.out.println("Question1:");
int num = reader.nextInt();
int end = (int)Math.log10(num);
for(int i = 0; i < end; i++)
System.out.printf("%d, ", get(num, i));
System.out.println(get(num, end));
System.out.println();
return this;
}
public Questions question2() {
System.out.println("Question2:");
int rand = (int)(Math.random() * 1000) + 1;
int times = 0, price;
while(true) {
price = reader.nextInt();
times++;
if(price > rand)
System.out.println("高了");
else if(price < rand)
System.out.println("低了");
else {
System.out.printf("恭喜!!!你用了%d次就猜对了\n", times);
break;
}
}
System.out.println();
return this;
}
public Questions question3() {
System.out.println("Question3:");
System.out.print("游戏开始吗?");
String choice = reader.next();
int a = 0, x = 0, y = 0, z = 0, machine, person;
if(choice.equals("开始")) {
do {
machine = (int)(Math.random() * 2);
person = (int)(Math.random() * 2);
a++;
if(machine == person) {
System.out.println("平局");
z++;
} else if(machine > person) {
System.out.println("机器赢了");
y++;
} else {
System.out.println("人赢了");
x++;
}
System.out.print("要继续吗?");
choice = reader.next();
} while(choice.equals("继续"));
System.out.printf("总共是:%d次\n", a);
System.out.printf("人 赢:%d次\n", x);
System.out.printf("机器赢:%d次\n", y);
System.out.printf("平 局:%d次\n", z);
}
System.out.println();
return this;
}
public Questions question4() {
System.out.println("Question4:");
double height = 100, sum = 0, lastHeight;
for(int i = 0; i < 10; i++) {
sum += height;
sum += height /= 2;
}
System.out.printf("第10次落地并反弹到最高点,共经过%f m\n", sum);
System.out.printf("第10次反弹%f m\n", height);
System.out.println();
return this;
}
public static void main(String[] args) {
new Questions().question1().question2().question3().question4();
}
}