|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
package test2;
import java.util.Random;
import java.util.Date;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
int num = (int)(random.nextInt(101));
System.out.println(num);
int i = 0;
String chs;
do {
while(true) {
long firstTime = System.currentTimeMillis();
System.out.println("请输入你猜测的数值: ");
int guess = sc.nextInt();
if(guess < num) {
System.out.println("你猜小了!");
i++;
}
else if(guess > num) {
System.out.println("你猜大了!");
i++;
}
else {
long secondTime = System.currentTimeMillis();
System.out.println("你猜对了!");
i++;
System.out.println("你一共猜了 " +i +"次。");
System.out.println("你一共用时:"+(secondTime - firstTime) / 1000+"秒");
break;
}
}
System.out.println("请选择是否继续游戏?请输入:Yes/No");
Scanner sca = new Scanner(System.in);
chs = sca.nextLine();
if(chs != "Yes") {
System.out.println("游戏结束");
}
}while(chs == "Yes") ;
}
}
代码如上,最后do while循环是想有一个继续游戏的功能,输入Yes则继续开始一局新游戏,但是实际上输入Yes后,游戏直接结束,不知道哪里错了,希望大佬们能看一看
- package test;
- import java.util.Scanner;
- import java.util.Random;
- import java.util.Date;
- public class test1 {
- public static void main(String[] args) {
-
- Random random = new Random();
-
- Scanner sc = new Scanner(System.in);
-
- int num = (int)(random.nextInt(101));
-
- System.out.println(num);
-
- int i = 0;
- String chs;
- do {
- while(true) {
- long firstTime = System.currentTimeMillis();
- System.out.println("请输入你猜测的数值: ");
- int guess = sc.nextInt();
-
- if(guess < num) {
- System.out.println("你猜小了!");
- i++;
- }
- else if(guess > num) {
- System.out.println("你猜大了!");
- i++;
- }
- else {
- long secondTime = System.currentTimeMillis();
- System.out.println("你猜对了!");
- i++;
- System.out.println("你一共猜了 " +i +"次。");
- System.out.println("你一共用时:"+(secondTime - firstTime) / 1000+"秒");
- break;
- }
- }
- System.out.println("请选择是否继续游戏?请输入:Yes/No");
- Scanner sca = new Scanner(System.in);
- chs = sca.nextLine();
- if(!chs.equals("Yes")) { //字符串比较不要使用‘==’下面while行同理
- System.out.println("游戏结束");
- }
- }while(chs.equals("Yes")) ;
- }
- }
复制代码
|
|