import java.util.Random; import java.util.Scanner; import java.io.*; //needed for file and IOException /** This program will demonstrate a guessing game. */ public class RandomNumberGuessingGame { public static void main(String[] args) throws IOException { // Constant for maximum random number final int MAX_NUMBER = 10; // Variables go here int guess; // Holds the users guess int randNum; // Holds the random number int count = 1; // Number of guess counter double guessScore; // Guess % String fileName; // Name of the file // Create the Scanner object Scanner keyboard = new Scanner(System.in); // Create a random object Random rand = new Random(); // Generate random number randNum = rand.nextInt(MAX_NUMBER); // Get the users guess System.out.println("I'm thinking of a number."); System.out.println("Guess what it is: "); guess = keyboard.nextInt(); // Make random number is greater than 0 // Respond to the user's guesses while (guess != randNum) { if (guess < randNum) { System.out.println("No, that's too low!"); count++; } else if (guess > randNum) { System.out.println("No, that's too high!"); count++; } System.out.println("Guess again: "); guess = keyboard.nextInt(); } //Congratuation the user System.out.println("Congratuation! You guessed it!"); System.out.println("I was thinking of the number " + randNum + "."); keyboard.nextLine(); //Terminate input buff. //Get the file name System.out.print("Enter the file name: "); fileName = keyboard.nextLine(); //Get output file name PrintWriter outputFile = new PrintWriter(fileName); //Calculate Guess Score guessScore = (((11-count)/11)*100); outputFile.println("Game Results"); outputFile.println("----------------------"); outputFile.println("Random Number: " + randNum); outputFile.println("Number of Guesses: " + count); outputFile.println("Guessing Score: " + guessScore + "%"); outputFile.close(); //close output } }
I have two problems.
1. I don't know how to make random number always greater than 0
2. when I calculate total score, i always get 0%. why is that? I tried to other division calculation but jgrasp always shows 0 if number is less than 1. for example if i do 10/5, it shows 2 which is right. but if I do 5/10, instead of shoing 0.5, it always shows 0. how do I fix this?
pseudo code
1. computer picks random number between 1 to 10
2. user input guess #
3. computer asks number over and over until user gets right one
4. display result
Game Results
---------------------------------
Random Number: (display answer)
Number of guesses: (display answer)
Guessing Score: (% accuracy guessing) - Feedback Message