该应用程序是一个简单的猜谜游戏,我得到了那部分。我的问题是制作一种方法,在任何猜测开始之前,玩家必须先猜出数字中正确的数字位数
例如,猜测为314且答案中有3位数,然后猜测太高的两个低位开始,否则它会一直循环直到你猜出正确的数字位数。
现在我已经创建了这样做的方法我认为这是一个相当简单的问题,但它是初始化变量的问题,以及我遇到问题的地方。
import java.util.Random;
import java.util.Scanner;
public class NumberGuess
{
public static void main (String[] args)
{
final int MAX = 1000;
int answer, guess;
Scanner Keyboard = new Scanner(System.in);
Random generator = new Random(); //Random generator. 1 to 100.
answer = generator.nextInt(MAX) +1;
guess = Keyboard.nextInt();
System.out.print ("I'm thinking of a number between 1 and "+ MAX + ". Guess what it is: (or enter 0 to quit) ");
do
{
System.out.print("Guess what the number is: ");
guess = Keyboard.nextInt();
if (guess > answer && guess != 0)
System.out.println("Your guess is too high!");
else if (guess < answer && guess !=0)
System.out.println("Your guess is too low!");
if(guess==0)
System.out.println("you have ended your game");
else if (guess == answer)
System.out.println("You got it!");
} while (guess != answer&& guess!=0);
}
int NumOfDigits(int number)
{
int numDigits = 0;
while (number/10 > 0);
{
number = number/10;
numDigits++;
}
return numDigits;
}
int guess;
Scanner Keyboard1 = new Scanner(System.in);
guess = Keyboard1.nextInt();
int target = NumOfDigits(answer);
while(NumOfDigits(guess) != target);
{
System.out.println("read anothrer input guess");
guess = Keyboard1.nextInt();
}
System.out.println("you got the correct number of digits now guess the number!");
guess = Keyboard1.nextInt();
}
答案 0 :(得分:0)
你计算diigits的方法是错误的应该是这样的
public static int NumOfDigits(int number)
{
int numofdigits = 0;
while(number>0){
numofdigits++;
number = number/10;
}
return numofdigits;
}
因为你的方法返回2并且它应该返回3