Today you\'ll write a Java program where the computer tries to guess a number th
ID: 3544661 • Letter: T
Question
Today you'll write a Java program where the computer tries to guess a number the human user has chosen. The user will choose a number between 1 and 10 but will not tell the computer about it. The computer will try to guess it by asking the user, "Is your number X?" with different values of X until the user says "yes", at which point the computer should print out a celebratory phrase like "Woohoo!".
Of course, this would be a very simple program to write if the computer just guessed the numbers 1-10 in order (Is your number 1? Is your number 2? Is your number 3? and so on). But what would be the fun in that? So we'll make the computer pick the numbers in random order. That introduces the problem of avoiding repeats--we don't want the computer to appear stupid by guessing the same number multiple times, so we'll have to keep track of what numbers we haven't guessed yet.
The basic approach you should use is to first build an array that has the numbers that haven't been guessed yet in it. So this will initially be an array of length 10 with the numbers 1-10 in it, probably just in order since that's the easiest way to populate the array.
To guess a number, use an expression that involves Math.random() to choose a random index in the array and guess the number at that index. So for instance, the first time through if the index you calculate is 2, the computer will say "Is your number 3?" because '3' is the value stored at index 2 in the array (recall that array indices are 0-based).
Here's the tricky part: once you've guessed a number, you don't want to guess it again, so you need to replace the array you have with a new array that includes everything before and after the number the computer just guessed, but not that number itself. This new array will be one element smaller than the previous one, of course. Continuing the example above, you'd replace your array that stored the values 1-10 with a new array that stores 1, 2, 4, 5, 6, 7, 8, 9, and 10 (since 3 was guessed).
The next time around, you need to make sure you use a modified expression with Math.random() to choose a valid index into your smaller array.
When your program is complete, submit it here.
You can assume that the user will be well-behaved and will guess a valid number, will answer questions honestly, will spell 'yes' correctly, etc. But if you are looking for a challenge, consider making your program more robust so it handles problems with user input. You do not need to do this to get full credit on the assignment.
Explanation / Answer
Hello
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.