猜数字 猜错再次键盘输入;猜3次算作猜中
package com.fqs.test;
import java.util.Random;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
//需求 程序自动生成一个1到100之间的随机数字A,键盘输入数B 猜数字
//1到10的随机数
Random r = new Random();
int ran = r.nextInt(10) + 1;
System.out.println("ran:"+ran);
//键盘输入
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("请输入猜的数字");
int num = sc.nextInt();
if (ran < num) {
System.out.println("猜大了");
} else if (ran > num) {
System.out.println("猜小了");
} else {
System.out.println("猜对了");
break;
}
}
}
}
猜三次算猜中
package com.fqs.test; import java.util.Random; import java.util.Scanner; public class hello { public static void main(String[] args) { //需求 程序自动生成一个1到100之间的随机数字A,键盘输入数B 猜数字 //1到10的随机数 Random r = new Random(); int ran = r.nextInt(10) + 1; System.out.println("ran:"+ran); //键盘输入 Scanner sc = new Scanner(System.in); int count=0; while(true){ //计数器 if(count==3){ System.out.println("猜3次,中了"); } System.out.println("请输入猜的数字"); int num = sc.nextInt(); if (ran < num) { System.out.println("猜大了"); break; } else if (ran > num) { System.out.println("猜小了"); } else { System.out.println("猜对了"); break; } count++; } } }