猜数字游戏怎么修改成由用户决定是否继续输入。
public class GuessNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ran = new Random();
int i = ran.nextInt(100);
System.out.println("请猜一下随机产生的数字:");
while (true) {
int j = sc.nextInt();
if (j == i)
System.out.println("恭喜你猜对了!");
else if (j > i)
System.out.println("sorry ,您猜大了!");
else if (j < i)
System.out.println("sorry ,您猜小了!");
}
}
}
加一句用户是否继续猜下去的提示,要求输入Y/y则继续,否则跳出循环
public class GuessNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ran = new Random();
int i = ran.nextInt(100);
System.out.println("请猜一下随机产生的数字:");
while (true) {
int j = sc.nextInt();
if (j == i)
{
System.out.println("恭喜你猜对了!");
break;
{
else if (j > i)
System.out.println("sorry ,您猜大了!");
else if (j < i)
System.out.println("sorry ,您猜小了!");
System.out.println("是否继续猜数字?输入Y/y继续:");
String s = sc.next();
if(s.charAt(0) != 'Y' && s.charAt(0) != 'y')
break;
}
}
}
在while循环内后面,增加一个提示“是否继续游戏”,对用户输入的值进行判断,如果是结束,就break结束循环。