I must ask the user to think of an integer between 1 and 1000. They do not type this number into the computer they just think of it.
- This program will make a random number.
- The user must indicate if the guess is too high, too low or correct (Hint the program can have the user type 1 for High 2 for low or 3 for correct)
- Your program will make another guess.
- The user must indicate if the guess is too high, too low or correct.
- This process goes on until the computer program guesses the users number. If you design your program correctly it should always guess the number in 10 tries or less.
Now I'm confused about its! I wrote this program but I don't know how to fix it.
public class NumberGenerating {
int generatedNumber;
public void generateRandomNumber(){
//generate a random number
this.generatedNumber=(int)(Math.random()*1000);
// System.out.println("Generated num is: "+this.generatedNumber);
}
}
and
import java.util.Scanner;
public class NumberGuessing {
byte count;
NumberGenerating newNumber=new NumberGenerating();
//boolean variable to determine if the loop should end
boolean shouldLoopEnd =true;
Scanner input=new Scanner(System.in);
byte userChoice;
int tempNumber, temp2Number;
int tempGenLowNumber=1000;
int tempGenHighNumber=1000;
int tempLowNumber;
// int tempLowNumberOld;
int tempHighNumber=1000;
// int tempHighNumberOld;
public void usingGenerateNumber(){
newNumber.generateRandomNumber();
}
public void isThatCorrect(){
this.temp2Number= newNumber.generatedNumber;
while(shouldLoopEnd){
System.out.println ("The computer guess number is: " + newNumber.generatedNumber);
System.out.println("You have three different choices:");
System.out.println("1. The guessed number was too high.\n"
+ "2. The guessed number was too low\n"
+ "3. The guessed number was correct!");
userChoice=input.nextByte();
if(userChoice==3){
System.out.println("Congratulation!\nGood Luck!");
shouldLoopEnd=false;
}
else if(userChoice==2){ //Call that the number was too low
// this.tempLowNumberOld=this.tempNumber;
while(true){
newNumber.generateRandomNumber();
this.tempNumber=newNumber.generatedNumber;
if(this.tempNumber>this.temp2Number && this.tempNumber<this.tempGenHighNumber //this.tempNumber>this.tempLowNumberOld &&
&& this.tempNumber<this.tempGenLowNumber){
this.tempGenLowNumber= this.tempNumber;
break;
}
}
}
else if(userChoice==1){ //Call that the number was too high
// this.tempHighNumberOld=this.tempNumber;
while(true){
newNumber.generateRandomNumber();
this.tempNumber=newNumber.generatedNumber;
if(this.tempNumber<this.temp2Number && this.tempNumber<this.tempGenLowNumber //this.tempNumber<this.tempHighNumberOld &&
&& this.tempNumber<this.tempGenHighNumber){
this.tempGenHighNumber= this.tempNumber;
break;
}
}
}
count++;
System.out.println("Loop number counter is: "+count);
}
}
}
and
import java.util.Scanner;
public class MainLoop {
public static void main(String[] args) {
NumberGuessing newNumber=new NumberGuessing();
newNumber.usingGenerateNumber();
newNumber.isThatCorrect();
}
}
You should actually never generate a random number (unless a homework criteria requires that of you).
Instead, you should guess 500. That number partitions the space from 1...1000 in half.
If the user's number is higher, guess 750 (mid-way between 500 and 1000). Continue to partition the range of possibly correct user numbers in half, until you reach the actual number.
If you do generate a new random number within the space of possibly correct numbers, you are not guaranteed to finish in 10 steps or less.
Related
So for my Java programming class one of the assesments is the following (a classic number guessing game):
Write a program that plays the HiLo guessing game with
numbers. The program should pick a random number between 11 (inclusive) and 88 (exclusive), then
repeatedly prompt the user to guess the number. On each guess, report to the user that he or she is
correct or that the guess is high or low. Continue accepting guesses until the user guesses correctly or
choose to quit. Use a sentinel value to determine whether the user wants to quit. Count the number of
guesses and report that value when the user guesses correctly. At the end of each game (by quitting or
a correct guess), prompt to determine whether the user wants to play again. Continue playing games
until the user chooses to stop. You are required to utilise at least a while loop and a for loop correctly.
So far, the game is fully working, using WHILE and IF functions. But in order to get full marks on my solution, it requires me to use at least one FOR loop, but I'm struggling to do that.
import java.util.*;
public class Guessing {
public static void main (String[] args)
{
//Setting up the variables
final int MAX = 88;
final int MIN = 11;
int answer, guess = 1;
String another="Y";
//Intializing scanner and random
Scanner scan = new Scanner (System.in);
Random generator = new Random();
//play again loop
while (another.equalsIgnoreCase("Y"))
{
//Generate a random number between 11 and 88
answer = generator.nextInt(MAX-MIN)+11;
System.out.print ("Guess the number I picked between "+MIN+" and "
+ MAX + "!\n");
while(guess!=answer)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!");
break;}
}
}
//Asking player to play another game
System.out.println("Do you want to play another game?(Y|N)");
another = scan.next();
if (another.equalsIgnoreCase("N"))
System.out.println("Goodbye, thank you for playing");
}
}
}
So far, the program works. It correctly gives higher/lower advice, the current round stops when typing in 0 as a guess and you can start another round with Y/N. But Im struggling to substitute one of the functions/loops with a FOR loop.
You can substitute the central while loop with a for loop that you can also use to count the number of iterations
for(int i=0;;i++)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!\n");
System.out.println("It took "+i+" guesses to get the answer");
break;}
}
}
This for loop is an infinite loop because it hasn't got the second argument. However your program will exit the for loop when the correct answer is given because of the break in the final else.
As the number of guesses is counted upwards, one may use the for loop on that.
Normally one would write for (int i = 0; i < n; ++i) { but here we want to know the loop counter after the for loop and have to declare it before:
int numberOfGuesses = 0;
for (; guess != 0 && guess != answer; numberOfGuesses++) {
}
... numberOfGuesses
There is no upper limit other than finding the answer or quiting.
All three parts in for (PARTA; PARTB; PARTC) are optional.
I really need help with this. Im using BlueJ and it says 'might not be initialized'. How do i fix it? its correctNumber roughly line 16ish.
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Random randomNumber = new Random();
int correctNumber;
int guessTracker;
int guessLimit = 6; //the number of tries
int userInput;
Scanner in = new Scanner(System.in);
int game = 1;
boolean winTracker = false;
while (1 == game)
correctNumber = randomNumber.nextInt(1100); //computer generates a random number, max 100
userInput = 0;
guessTracker = 0;
System.out.println("Hello and welcome to this number guessing game. Please guess the number between 1 and 100 and I will help you by telling you if your guess is too high or low: ");
while (**correctNumber** != userInput && guessTracker < guessLimit){
userInput = in.nextInt();
guessTracker++;
if (userInput == correctNumber){
System.out.println("You have won the game! Your reward is a fact game: Did you know the first working camera was invented in 1816! "); //winner message, with a unlocked fact game
System.out.println("The correct number was " + correctNumber); //the correct number
System.out.println("It took a total of " + guessTracker + " guesses"); //number of guesses it took the user to guess the right number.
}
else if (userInput < correctNumber){
System.out.println("Your number is too low"); //displays that the users guess is too low
System.out.println("Please enter your next guess: "); //// user can now eneter their next guess
}
else if (userInput > correctNumber){
System.out.println("Your number is too high"); //displays that the users guess is too high
System.out.println("Please enter your next guess: "); // user can now eneter their next guess
}
if (correctNumber != userInput){
System.out.println("Sorry you have run out of guesses! The correct number was: " + correctNumber); // displays the correct number
}
}
}
}
You need to initialize correctNumber to a value.
This is not always the case, but think about this:
you call while(1 == game) which then initialized correctNumber to a random number, correctNumber = randomNumber.nextInt(1100) this would initialize correctNumber, but when the java compiler compiles your application it can't be sure that 1 == game is true. Therefore, when the compiler gets to the next loop while (**correctNumber** != userInput && guessTracker < guessLimit) your compiler sees that correctNumber has not been initialized even though it would be by the first loop.
In short, the compiler does not know whether a loop will be entered or not, therefore user3437460 is absoultely correct in saying that you need to initialize local scope variables, in this case int correctNumber = 0 will work perfectly for you.
I really need help with this. Im using BlueJ and it says 'might not be initialized'. How do i fix it?
Local scope variables need to be initialized (assigned an initial value) before use:
int correctNumber = 0
Same applies for your other variables.
I'm trying to make a small gambling game in Java where the user has two options.
A TextField where he can write in the amount of how much he wants to bet and a ComboBox where he can choose how many precent chance for him to win. The comboBox provides the options 10%, 20%, 30%, 40% and 50%.
My problem is that I don't know how to apply probability in java. I tried doing following:
public class GamblingGame {
private int rdmNumber;
private int wonValue;
public int winOrLose(int valueBetted, int precentToWin, Label label, int attempts){
precentToWin = precentToWin/10;
rdmNumber= ThreadLocalRandom.current().nextInt(precentToWin, 10 +1);
System.out.println("this is rdmnumber: " + rdmNumber);
System.out.println("this is precentowin number: " + precentToWin);
//if the number you rolled is equal to the precent you choose (ie if its 10, the number is 1, if its 20 the number is 2)
if(rdmNumber == precentToWin) {
wonValue = valueBetted/precentToWin *2;
System.out.println("You win!");
label.setStyle("-fx-text-fill: green");
label.setText("You won! You recieved: " + wonValue+" coins!");
}
else{
label.setStyle("-fx-text-fill: red");
label.setText("Gamble failed! You lost: " +valueBetted + " coins. ("+attempts+")");
wonValue = -valueBetted;
}
System.out.println(wonValue);
return wonValue;
}
}
The problem is that if, for instance, the user puts in 50% in the combobox he won't get a true 50% chance to win.
The number the dice would need to roll here is 5 in order to win, and the max value is 10. So the user would roll a number between 5-10 and when he hits 5, he'd win.
How do I make it so that the precentage of rolling the dice would be a true 50%? (and of course not ruin it so that if i put in a difference precentage as the parameter it wont ruin the method)
how about you try this function?
private static Random rd = new Random();
public static boolean winner(int prob)
{
int value = rd.nextInt(100);
System.out.println("GOT: "+value+" probability of winning:"+prob+"%");
if(prob>value)
return true;
else
return false;
}
in this case, the probability num should be bigger to the obtained random number.
so, if you run this.. it will work
public static void main(String[] args) {
//sure winner
System.out.println(winner(99));
//random winner
System.out.println(winner(50));
//not a chance
System.out.println(winner(10));
}
try Random
Random random = new Random();
int i = random.nextInt(100);
if(i<50){
//do something
}
Thank you so much to both people who replied! It made me realise all i had to do was change following.
rdmNumber= ThreadLocalRandom.current().nextInt(1, 10 +1);`
if(rdmNumber <= precentToWin)
so now, the numbers itll look through will always be 1-10, but the possiblities of getting it right won't be one number, but multiple numbers.
Thanks again!
Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!
I am trying to create a die rolling program. The goal is to roll a die until the chosen value comes up a certain number of consecutive times (I used the programmer defined name "rollLength" for this). I am trying to display how many total rolls it took until the die value comes up consecutively. The problem is when I run the program it shows that the rollLength came up perfectly with no wasted rolls which I know is unrealistic. My question is if you can suggest what is wrong with my code. I am not sure if I am doing nested loops wrong.
Here is my code.
package lab03_schultz;
import java.util.Scanner;
import java.util.Random;
public class Lab03_Schultz {
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
//declare variables
int value, nSides, rollLength, roll;
int turns=0, n=0, count=0, totalThrows=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
while(n!=value) {
roll = randomNumber.nextInt(nSides)+1;
n++;
}
while(count!=rollLength){ //countinue till count = rollLength
if(n==value){
count++; //count how many times n == value, this is to represent consective rolls for the value
} else if (n!=value) { //if n is not the value counter starts over at zero
count=0;
}
if (n!=value) {//This will count how many times the die didn't come up with the value
totalThrows++;
}
}
System.out.println("totalThrows: " + totalThrows); //finding what totalThrows is
//adds rolls (without watched value) and (when it showed watch value) together
System.out.println("Your total throws are: " + (totalThrows+rollLength));
}
}
This can be done with just a single loop
int rollsInARow = 0; // store how many times we roll the value
int totalThrows = 0;
while(rollsInARow != rollLength) {
int roll = randomNumber.nextInt(nSides)+1;
if(roll == value) {
rollsInARow++; // Count consecutive rolls that are the wanted value
} else {
rollsInARow = 0; // Reset if we get a roll other than value
}
totalThrows++; // +1 after each roll
}
We loop until we have the wanted rollLength. Each loop generates a random number and compares it to value. If they are equal, increment the counter. If different, reset the counter. At the end of each loop, keep track of total rolls.
Also a tip. When using an if statement to check a true/false value (n == value), you can simply use an else statement to catch the n != value because there are only two cases.
if(n == value) {
count++;
} else { // The same functionality as else if(n != value)
count = 0;
}
Your first while loop will run until n is equal to the value. It will not move past that block of code until n is equal to value.