Java初学者心得
学一样东西需要把他当做兴趣来学,才能事半功倍,做什么都要有恒心,初学的时候,可以挑自己感兴趣的先学,不懂的可以暂且跳过,等你学会后面的之后回过头来看,就会发现曾经不会的原来那么简单.
Java初学猜数字游戏代码
```java
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class CaiShuiZi {
public static void main(String[] args) {
Random r = new Random();
int min = 1;
int max = 100;
int count = 0;
System.out.println("游戏开始");
int sui = r.nextInt(100) + 1;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入一个" + min + "-" + max + "的数字");
try{
int cai = sc.nextInt();
count++;
if (cai < sui && cai >= min) {
min = cai;
System.out.print("太小了,");
} else if (cai > sui && cai <= max) {
max = cai;
System.out.print("太大了,");
} else if (cai < min || cai > max) {
System.out.print("你的输入有误,");
} else if (cai == sui) {
System.out.println("哦耶。恭喜你只用了" + count + "次就猜对了是否新的游戏y/n");
String s = sc.next();
if (s.equals("y")) {
System.out.println("新游戏开始");
min = 1;
max = 100;
count = 0;
sui = r.nextInt(100) + 1;
} else {
System.out.println("game over");
break;
}
}
if (count>=10){
System.out.println("你太笨了,"+count+"次都猜不对,正确数字是"+sui+"是否开始新的一局y/n");
String s = sc.next();
if (s.equals("y")) {
System.out.println("新游戏开始");
min = 1;
max = 100;
count = 0;
sui = r.nextInt(100) + 1;
} else {
System.out.println("game over");
break;
}
}
}catch (InputMismatchException e){
// sc.skip(".");
//e.printStackTrace();
System.out.println("你的输入有误。");
sc = new Scanner(System.in);
}
}
}
}
更多推荐
Java初学者心得之猜数字游戏标准简单版
发布评论