Java Guessing game 'might not be initialized' - java

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.

Related

i need to output the final part of my JAVA program which is just a game over string , how can i insert it?

these is my program i need to output "game over" if the user enter the string no instead of yes, right now it only works with the yes but i dont know how to add the other option the game is suppose to ask the user for a seed , then for a number from 1 to 100 and then the user has to guees the number, once the user guesses the number it asks if it wants to play again, with option of yes or no, i have the yes but i dont know how to output the no.
import java.util.Random;
import java.util.Scanner;
public class GuessANumber_part2 {
public static void main(String[] args) {
//Method generates a random number and per user's
//input it prints if is to low, to high or the
//correct number
guessNumber();
}
public static void guessNumber() {
//Generating a seed number
System.out.println("Enter a seed:\n");
Scanner scanner = new Scanner(System.in);
int seed = scanner.nextInt();
//variable counts number of guesses
int guess;//variable holds user's guess
boolean play = true;//variable to run while
//Generating random object
Random random = new Random(seed);
int correctNum = random.nextInt(100) + 1;
//Outer loop count the amount of guesses
//Prompts user to play the game again
while(play) {
//welcome statement, getting the initial input
System.out.println("Welcome!\n"
+ "Please enter a number between 1 and 100:");
//variables
guess = scanner.nextInt();//saves the initial input
int count = 1;//count the number of guesses
//Inner loop outputs if the number given by the user
//is either to high, to low or if is the correct number
while( guess != correctNum) {
if(guess < correctNum) {
System.out.println("Too low. Guess again:");
}else if(guess > correctNum) {
System.out.println("Too high. Guess again:");
}
count++;// keeps count of N of guesses
//welcome message and input statement
System.out.println("Welcome!\n"
+ "Please enter a number between 1 and 100:");
guess = scanner.nextInt();
}
//outer loop statement,Prompts the user to run or
//not run game again
System.out.println("Congratulations. You guessed correctly!\n"
+ "You needed " + count + " guesses.\n");
System.out.println("Do you want to play again? Answer \"yes\""
+ " or \"no\":");
//Output statement sets play to answer "yes"
play = scanner.next().toLowerCase().equals("yes");
}
}
}

"Guess My Number" game with only allow 3 guesses from user

I've created many different types of method in my coding as my task requires to, so I faced some problems that I'm trying to incorporate loops that allow only 3 guesses from the user. After each round, the user has the option of whether to continue playing or to stop. How should I implement that? Also, any mistakes in my coding? Thank you in advanced!
import java.util.Random;
import java.util.Scanner;
public class GuessmyGame{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100)+1;
printInstruction();
int guess = in.nextInt();
guessNum(number, guess);
numberOfTries(guessNum);
}
public static void printInstruction(){
System.out.println(" I am thinking of a number between 1 and 100.");
System.out.println(" Can you guess what it is? ");
System.out.println(" Type a number : ");
}
public static void guessNum(int number, int guess){
if (number == guess){
System.out.println("Congratulations! You got it right.");
}
else if(number > guess){
System.out.println("Your guess is too low.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
else{
System.out.println( "Your guess is too high.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
}
public static void numberOfTries(int guessNum){
Random random = new Random();
int number = random.nextInt(100)+1;
for(int i = 0; i < 3; i++){
System.out.println("Out of guesses!");
System.out.println("The number was " + number);
}
}
}
Use a while loop and add a boolean condition.. let's call it canContinue. You'll also need to keep track of how many times the user has attempted to guess, let's say it's called attemptCount as well as the correctness of the user's latest guess (correctGuess).
When attemptCount is 3 or correctGuess is true, prompt the user if they want to continue. If their answer suggests they don't want to continue, set canContinue to false, which causes the exit the loop and complete. Otherwise, reset attemptCount (to 0 presumably to allow another 3 attempts). The code that follows highlights the requested logic. since it's clear the code provided in the question has many bugs.
var promptToRetry = false;
while (canContinue) {
if (correctGuess) {
// Let user know their guess was correct
promptToRetry = true;
}
if (attemptCount > 2) {
// Let user know they didn't get the right number
promptToRetry = true;
}
if (promptToRetry) {
boolean wantsToTryAgain = PromptUserToTryAgain(); //Code returning bool which prompts user if they want to try again (need to implement)
if (wantsToTryAgain) {
attemptCount = 0; //Resets attempt counter
correctGuess = false; //Resets the guess
promptToRetry = false;
} else {
canContinue = false; //Causes loop to exit
}
}
...
}
}

Java number guessing

a. declare a final int, and assign a value of 6 as the guessed number
// b. create a Scanner to get user input
// c. use a do {} while loop to prompt the user to enter an integer between 1 and 10,
// assign the user input to an int, and compare to the guessing number
do{
} while ();
// d. if the number matches the guessed number,
// print out a message that the number entered is correct.
I am stuck on the do while loop portion of the problem
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
int value = 6;
int guess = 0;
int num = 0;
do {
System.out.println("Please enter a number between 1 and 10: ");
Scanner number = new Scanner(System.in);
guess = number.nextInt();
} while (num <= 10);
if (guess == value);
System.out.println("Congratulations you guessed the correct number!");
if (guess != value);
System.out.println("The number does not match.");
}
}
This is the result I am getting. I cannot figure out why it wont print the messages saying the number is correct or the number did not match.
Please enter a number between 1 and 10:
4
Please enter a number between 1 and 10:
5
Please enter a number between 1 and 10:
6
The semicolon after the if statement stops it from working and makes no sense
if (guess == value);
^ No no no
Should be
if (guess == value) {
System.out.println("Congratulations you guessed the correct number!");
}
Or
if (guess == value)
System.out.println("Congratulations you guessed the correct number!");
You should also increment num or the while makes no sense
Remove the Semicolon after the ifstatement, and i strongly advise you to use {} to wrap all your statements.
Morover you should increase num inside your while loop, and move the guessing part inside your while loop. so the correct messages are printed out in every loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int value = 6;
int guess = 0;
int num = 0;
do {
System.out.println("Please enter a number between 1 and 10: ");
Scanner number = new Scanner(System.in);
guess = number.nextInt();
num++;
if (guess == value) {
System.out.println("Congratulations you guessed the correct number!");
break;
}
if (guess != value) {
System.out.println("The number does not match.");
}
} while (num <= 10);
}
}
You code basically looks like this:
ask user for a number from 1 to 10
and do this forever
now check whether the number entered is the right guess
So as long as the user does what he is told, you keep asking and reasking. You never get to "now check...".
The loop needs to encompass the checking for the right guess, and needs to be terminated on the right guess.
(Edited) I slightly misread the original code, thinking that 'num' was the input value. Nope, the input number is called 'number'. I suggest the counter be renamed for clarity, maybe 'guessCount'. And of course remember to increment it with each guess.

Implement/Substitute WHILE Loop with FOR Loop in number guessing game

So for my Java programming class one of the assesments is the following (a classic number guessing game):
Write a program that plays the Hi­Lo 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.

Adding message when certain condition is met (Java)

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!

Categories