我正在为一个项目工作,要求我使用while和for循环生成两个版本的猜谜游戏。分配的最后一部分是创建一个Driver类来调用GuessGame类中的两个游戏版本。出于某种原因,我的驱动程序在运行时不会执行while循环以允许用户输入他们的选择以选择要使用的游戏版本。有什么帮助吗?
GuessGame代码:
import java.util.Scanner;
public class GuessGame
{
public static void example()
{
Scanner in = new Scanner(System.in);
System.out.println("Give me a number:");
int num = in.nextInt();
System.out.println("You gave me " + num);
}
public static void roll1()
{
int guess = 1;
int randomNumber = (int) (Math.random() * 10) + 1;
Scanner scan = new Scanner(System.in);
boolean win = true;
System.out.println("I'm thinking of a number between 1 and 10.");
while (win)
{
System.out.println("What is your guess?");
guess = scan.nextInt();
if (guess == randomNumber)
{
System.out.println("You guessed it!");
break;
}
else if (guess > randomNumber)
{
System.out.println("Smaller!");
}
else if (guess < randomNumber)
{
System.out.println("Bigger!");
}
}
}
public static void roll2(int num)
{
int guess = 0;
int randomNum = (int) (Math.random() * 20) + 5;
Scanner scan = new Scanner(System.in);
boolean win = true;
System.out.println("I'm thinking of a number between 5 and 25");
for (int guessNum = 0; guessNum < num; guessNum++)
{
System.out.println("What is your guess?");
guess = scan.nextInt();
if (guess == randomNum)
{
System.out.println("You guessed it!");
break;
}
else if (guess > randomNum)
{
System.out.println("Smaller!");
}
else if (guess < randomNum)
{
System.out.println("Bigger!");
}
}
}
}
驱动程序代码:
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
GuessGame game = new GuessGame();
int choice = 1;
System.out.println("Guessing Game");
System.out.println("-------------");
while (choice != 1)
{
System.out.println("1. Version 1");
System.out.println("2. Version 2");
System.out.println("3. Quit");
System.out.println("\nPlease enter your choice > ");
choice = in.nextInt();
System.out.println();
switch (choice)
{
case 1:
System.out.println("Version 1:");
game.roll1();
break;
case 2:
System.out.println("Version 2:");
game.roll2(5);
break;
case 3:
System.out.println("Thanks for playing.");
break;
default:
System.out.println("Invalid choice.");
}
}
}
}
很抱歉格式化问题,第一次使用此网站。
答案 0 :(得分:0)
你的状况永远不会成真;
您将choice
声明为
int choice = 1;
然后你说:
while (choice != 1)
{
//stuff
}
因为choice被声明为= 1,所以循环永远不会自行完成。另一种方法是宣布选择如下
int choice = -1;
另一种方法是使用do while
构造。