populate ArrayList with user input - java

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.

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");
}
}
}

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.

Java Guessing game 'might not be initialized'

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.

Using try/catch to alert user of negative number entered, nestled in loop

I have created a program to find the average of positive numbers only. The program works fine, however, I am looking to improve it. At the moment when a user enters a negative number the loop ignores it. However I would like an error message to come up once the user enters a negative number.
I have done some research and I believe I need to add a try catch within my loop however, I'm not sure how I would implement it into my existing code.
Here is my code so far;
System.out.println("program to find the arithmetic mean (average) of a list of positive numbers ");
System.out.println("=======================");
System.out.println();
System.out.print("How many numbers do you want to enter ? ");
numbers = inputLine.nextInt();
System.out.println("Enter " +numbers+ " Numbers : ");
for (start=0; start<numbers; start++) {
int number;
do {
number = inputLine.nextInt();
} while (number < 0);
sum = sum + number;
}
if (numbers == 0) {
System.out.print("program terminated......");
System.exit(0);
}
armean = sum/numbers;
System.out.print("Average of all positive numbers entered is: " +armean);
You don't need a try-catch since you don't get any exceptions here. User entering negative numbers is completely legitimate case. Just add some error message inside you do-while loop. E.g.
do {
number = inputLine.nextInt();
if (number < 0)
System.out.println("Does not compute! Enter a positive number!");
} while (number < 0);
Why do you need try-catch? You can simply check if the input number is negative and display an error message using println().

In Java, is it possible to use some sort of while loop (or anything) to determine the amount of prompts for input?

public static void main (String [] args)
{
// declare variables, capture input
String input, name = JOptionPane.showInputDialog("Please " +
"enter your first and last name.");
double testScore1, testScore2, testScore3, average;
// capture input, cast, and validate input
input = JOptionPane.showInputDialog("What is the score " +
"of your first test?");
testScore1 = Double.parseDouble(input);
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your second test?");
testScore2 = Double.parseDouble(input);
while (testScore2 < 1 || testScore2 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore2 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your third test?");
testScore3 = Double.parseDouble(input);
while (testScore3 < 1 || testScore3 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore3 = Double.parseDouble(input);
}
// calculate average and display output
average = (testScore1 + testScore2 + testScore3)/3;
JOptionPane.showMessageDialog(null, name + ", your average score is: " + average);
}
First off, I'm a beginner programmer. My terminology and jargon are quite lacking, so bear with me.
I'm writing a program to capture 3 test scores then validate them using a while loop (must be within the 1-100 range). The test scores are then averaged and the output displays the average. Pretty simple stuff.
I'm wanting to find a way, if possible, to capture the number of test scores, then from there, capture each actual score. For example, the program asks "How many tests are being computed for average?", then take that number and have it be the same amount of times the program prompts, "Please enter test score (1):" or something along those lines. So for further clarity, if the user typed 4 for number of tests, then the prompt for inputting the score would show up 4 times.
I feel the above code is redundant by using a while loop for each score and at that, limited because the program is only meant for 3 scores. Any help is much appreciated and feel free to critique anything else in the code.
Yes you can.
What you need is a nested loop. In pseudo code:
while(condition)
{
int numberOfInput = getInput() ; //get the input from the user
for(int i =0 ; i < numberOfInput; i++) //iterate for the amount of prompts required
prompt() ; //get input
}
function prompt
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
Short answer:Yes, it is possible.
Option 1: Initially ask the user how many scores they are planning on entering, and store that in an int variable.
For example:
Ask user how many scores to enter.
Check the response, and store it in an int variable.
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable
Once loop is exhausted, just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Option 2: Use a sentinel-loop (the user has to enter a letter -usually 'Q' or 'N'- or something to exit the loop)
Create an int variable to store total loops (initialize to 0).
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Check if the value is the quit character
If it is not
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable and increment
the total loops variable by 1.
If it is
just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Hope it helps.
In http://korada-sanath.blogspot.in/p/discussion-on-tech-topics.html, there is a pseudo code which illustrates similar problem with basic Java programming skills. In that in looping section you can simply add a check whether user entered score is in range 1-100 or not. If not, you can decrease loop variable by '1' so that user can enter his score one more time...
For further illustration please add below code in looping section of code present in above mentioned link.
instead of directly assigning user entered value to your testScores array, you can use one temp var and then can assign if user entered score in range.
Double temp = Double.parseDouble(br.readLine());
if(temp > 1 && temp < 100) {
testScores[loopVar] = temp;
} else {
loopVar--;
}

Categories