Код:Отсутствие исключения элемента. Я застрял
package FisherTCh5Sec4to5;
import java.util.Scanner;
public class FisherTCh5Sec4to5 {
public static int generateRandomInt(int lowerLimit, int upperLimit){
int range = (upperLimit - lowerLimit) + 1;
int randomInt = (int) Math.random() * range + lowerLimit;
return randomInt;
}//end generate random int
public static int collectInteger(String purpose, int minimum, int maximum){
Scanner in = new Scanner(System.in);
int userInt = 0;
boolean done = false;
do {
System.out.printf(purpose);
if (in.hasNextInt()){
userInt = in.nextInt();
if (userInt >= minimum && userInt <= maximum){
done = true;
} else System.out.printf("That number isn't in the desired range.\n");
} else System.out.printf("Sorry...I can't use that input.\n");
//Clear input stream
in.nextLine();
} while (!done);
in.close();
return userInt;
}// end method
public static void main(String[] args) {
// Variables
final int LOWER_LIMIT = 1;
final int UPPER_LIMIT = 10;
boolean done = false;
String playAgain = "";
int count = 0;
int wins = 0;
// Open input stream
Scanner in = new Scanner(System.in);
do {
// Use collectInteger to get a number
int userInput = collectInteger("Let's play a game! Try and guess my number (between 1 and 10): ", LOWER_LIMIT,
UPPER_LIMIT);
// use generateRandomInt to get a number
int randomInt = generateRandomInt(LOWER_LIMIT, UPPER_LIMIT);
// If statement to decide a win or loss
if (userInput == randomInt){
System.out.printf("Congrats you win! My number was %d.\n", randomInt);
wins++;
} else System.out.printf("Sorry...my number was %d.\n", randomInt);
// Ask user to play again
System.out.print("Would you like to continue? (\"c\" to continue \"q\" to quit): ");
playAgain = in.next();
if (playAgain.equals("c")){
done = false;
} else done = true;
count ++;
} while(done = false);
// Print and calculate win percentage
double winPercent = (wins/count) * 100;
System.out.printf("Wow! Your win percentage was %.2f%%.\n", winPercent);
// close input stream
in.close();
}//end main
}//end class
Все работает прекрасно для части «Вы хотите, чтобы играть снова», за исключением. Думаю, он не позволит мне читать данные пользователя. Есть идеи?
Просто отсутствует! = –