在用户输入猜测之前,阵列正在打印。我确定它在错误的位置。我需要数组来记录猜测的次数,然后当用户最终猜出正确的数字时,我需要它来打印出它所花费的尝试次数。最后我会添加回合,但我想确保在我这样做之前可以正确打印阵列。
// "Guess My Number"
import java.util.Random; //program uses random
import java.util.Scanner; //program uses scanner
public class GuessMyNumber{
public static void main(String[] args){
Scanner input = new Scanner ( System.in );
int randomNum;
int userNum;
int counter;
Random randomNumbers = new Random();
randomNum = 1 + randomNumbers.nextInt(11);
counter = 1;
System.out.println( "Enter a number (no decimals) from 1 to 1000: \n" );
userNum = input.nextInt();
int[] guess;
guess = new int[ 99 ];//array of 100 guesses
for (int guesses = 0; guesses < guess.length; guesses++ ){
System.out.printf("%5d%8d\n", guesses, guess[guesses] );
}
while (userNum != randomNum){
if (userNum < randomNum){
System.out.printf( "%d is too low! Please pick another number.\n", userNum);
++counter;
}
else if (userNum > randomNum){
System.out.printf("%d is too high! Please pick another number.\n", userNum);
++counter;
}
userNum = input.nextInt();
}
System.out.println( "\nCongratulations! You guessed the right number.\n");
System.out.printf( "It took you %d tries!", counter);
}
}
答案 0 :(得分:2)
您需要为'guess'的每个元素指定一个值。
for (...) {
guess[guesses] = guesses; // or something else
System.out.printf(...)
}