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.
Related
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");
}
}
}
I am making an odd or even program with a while loop. I am trying to figure out how to end the while loop with a certain number. Right now I have 1 to continue the loop, and trying to make 2 the number that terminates it. Also trying to figure out how to terminate the program if a user types anything but a number like a letter/words.
package oddoreven;
import java.util.Scanner;
public class oddoreven {
public static void main (String[] args){
int num;
int x = 1;
while(x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
You should try to use "a real termination condition" in order to terminate a while loop (or any loop for that matter); it's cleaner and should be easier to understand by everyone else.
In your case, I think it's better to have a do-while loop with some condition around this logic: num % 2 == 0, and an inner while loop for handling user input/validation.
If you still want to break loops abruptly, have a look here.
If you still need some help with the code, hit me up and I'll sketch up something.
I did not follow the conditions you wanted exactly because it does not make sense to have a continue condition AND a terminate condition unless there are other options.
What did you want the user to do if he entered 3, 4 or 5? Exit the code or continue the code? Well if the default is to exit, then you do not need the code to exit on 2 because it already will! If the default is to continue, then you do not need the continue on 1 and only the exit on 2. Thus it is pointless to do both in this case.
Here is the modified code to use a do while loop to ensure the loop is entered at least 1 time:
int x;
do {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
int num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to check another number, anything else to terminate.");
if (!s.hasNextInt()) {
break;
}
else {
x = s.nextInt();
}
} while(x == 1);
}
Note that I added a check to !s.hasNextInt() will check if the user enters anything other than an int, and will terminate without throwing an Exception in those cases by breaking from the loop (which is the same as terminating the program in this case).
If the x is a valid integer, then x is set to the value and then the loop condition checks if x is 1. If x is not 1 the loop terminates, if it is it will continue through the loop another time.
Another thing you can try is that instead of exiting the program you can just keep asking user to enter correct input and only proceed if they do so. I don't know what is your requirement but if you want to go by good code practice then you shouldn't terminate your program just because user entered wrong input. Imagine if you googled a word with typo and google just shuts off.
Anyways here is how I did it
import java.util.Scanner;
public class oddoreven {
public static void main(String[] args) {
int num;
int x = 1;
while (x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
boolean isInt = s.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
s.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
num = s.nextInt(); // If it is int. It reads the input
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
// trying to figure out how to get the code to terminate if you put in a value
// that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
To exit the program when the user enters anything other than a Number, change the variable x type to a String
if (!StringUtils.isNumeric(x)) {
System.exit(0);
}
To exit the program when user enters 2
if (x == 2) {
System.exit(0);
}
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.
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 sure this has been asked 1000 times, but I cannot fig this out for the life of me. I have searched stack overflow, google, code ranch etc. and cannot find what I am looking for. I need to be able to take a number and add it to an ArrayList when it is generated. The program generates a random number and then ask the user to try and guess what it is. I can get the number of guesses to populate correctly, but I cannot get it to store in the ArrayList. I need each guess to be in a new index, and I do not know how many I will need due to how many games the user decided to play. I am not even sure if the ArrayList is what I need to use. The point of storing them is so I can find the greatest number of guesses for later in the program. Here is my code for guessing the number and displaying it to the user. I am using guesses as the int to store the info from the users guess. I am new to JAVA, so please excuse all the comments to keep me on track.
public static void guessNumber() {
//Totals the games played by the user
gamesPlayed++;
//Scanner to allow user input
Scanner console = new Scanner(System.in);
//Prints "Your guess ? " for the user to input their guess
System.out.print("Your guess ? ");
// Input for the number the user guessed
int numberGuessed = console.nextInt();
//While loop with nested if statement to check if the number guessed by the user is equal to the random number generated, if not,
//show higher or lower hints depending on the guess
while (numberGuessed != randomNumber) {
//if statement to determine if the guess is higher or lower than the random number
//if the guess is higher, show the random number is lower than the guess, than ask the user to guess again
if (numberGuessed > randomNumber) {
//Prints "lower" for the user to know the number is lower than the guess,
//Prints "Your guess ? " for the user to guess again
System.out.println("lower");
System.out.print("Your guess ? ");
//End of if statement and begins else if statement to determine if the guess is higher or lower than the random number
//If the guess is lower, show the random number is higher than the guess,
//Prints "Your guess ? " for the user to guess again
} else if (numberGuessed < randomNumber) {
//Prints "higher" for the user to know the number is higher than the guess,
//"Your guess ? " for the user to guess again
System.out.println("higher");
System.out.print("Your guess ? ");
}// End of else if statement
// Input for the number the user guessed
numberGuessed = console.nextInt();
//Counts the number of tries it took to guess the correct number
guesses++;
//Totals all the guesses made in the games played
totalGuesses++;
}//End of while loop
//Array for storing guesses
System.out.println("");
ArrayList<Integer> test = new ArrayList<Integer>();
for (int i = 0; guesses > i; i++) {
test.add(guesses);
System.out.println("Elements of ArrayList of Integer Type: "+ test);
}
//Shows the user guessed the right number and how many tries it took to guess the number
System.out.println("You got it right in " + guesses + " guesses" + "\n");
//Ask the user if they want to play again
System.out.print("Do you want to play again? ");
//Input for the user to input yes or no if they want to play again or not
String playAgain = console.next();
//Prints blank line
System.out.println("");
//Totals all the guesses made in the game
double endingTotalGuesses = totalGuesses + gamesPlayed;
//If statement to check and see if the user wants to play again and ignores the case of the word no
if (playAgain.equalsIgnoreCase("yes")) {
//Resets the number of guesses when a used starts a new game
guesses = 1;
//Prints I'm thinking of a number...
System.out.println("I'm thinking of a number...");
//Calls the generateRandomNumber method to pick a random number to guess
generateRandomNumber();
//Assigns the generateRandomNumber method to the integer randomNumber
randomNumber = generateRandomNumber();
//*Remove this line that shows what the number is!*
System.out.println("The number is: " + randomNumber);
//Calls the guessNumber method to allow the game to start over and the user to start guessing
guessNumber();
//End of if statement and starts the else if statement to see if the user wants to play again and ignores the case of the word no
} else if (playAgain.equalsIgnoreCase("no")) {
//else if statement. If the user chooses no, it will call the endOfGames method and pass the
//ending amount of guesses and total of games played
endOfGames(endingTotalGuesses, gamesPlayed);
}//end of else if statement
}//End of guessNumber method
The only place it appears you're using a List is here:
System.out.println("");
ArrayList<Integer> test = new ArrayList<Integer>();
for (int i = 0; guesses > i; i++) {
test.add(guesses);
System.out.println("Elements of ArrayList of Integer Type: "+ test);
}
In each iteration through the loop, you are adding the exact same values, which is the integer referenced by guesses. E.g., if it took 5 guesses, you'd be adding the number 5 to the array 5 times.
You'll dereference test every time you exit guessNumber(), so in order to keep it in scope, you either need to do something useful with it there, or have a class-level ("field") variable reference the ArrayList.
Also, I noticed that you're calling generateRandomNumber() needlessly twice:
//Calls the generateRandomNumber method to pick a random number to guess
generateRandomNumber();
//Assigns the generateRandomNumber method to the integer randomNumber
randomNumber = generateRandomNumber();
The first time is wasted -- its returned value is unused.