why is my program displaying the array wrong? - java

I am having a problem with my program. When I compile and run my program everything runs great until it's time to display the guesses back to the user. when that happens the last guess always gets displayed as 0.
My assignment is to develop a program that simulates the high-low game. For each execution of the program, the game will generate a random number in the inclusive range of 1 to 100. The user will have up to 10 chances to guess the value. The program will keep track of all the user’s guesses in an array. For each guess, the program will tell the user if his/her guess was too high or too low. If the user is successful, the program will stop asking for guesses, display the list of guesses, and show a congratulatory message stating how many guesses he/she took. If the user does not guess the correct answer within 10 tries, the program will display the list of guesses and show him/her the correct value with a message stating that he/she was not successful. Regardless of the outcome, the program will give the user a chance to run the program again with a new random number.
This is what I have so far:
import java.util.Random;
import java.util.Scanner;
/**
*
* #author jose
*/
public class Assignment7
{
/*
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number;
String again = "y";
while (again.equalsIgnoreCase("y"))
{
int[] guesses = new int[10];
int tries = 0;
number = GetRandomNumber(1, 100);
System.out.println(number); // delete before submitting
int userGuess = GetUserGuess(1,100);
while (userGuess != number && tries < guesses.length - 1 )
{
guesses[tries] = userGuess;
LowOrHigh(number, userGuess);
userGuess = GetUserGuess(1, 100);
tries++;
}
if (tries != 10)
{
userGuess = guesses[tries];
tries++;
System.out.println("Congratulations! You were able to guess the correct number");
}
else
{
System.out.println("Sorry! You were not able to guess the correct number");
}
if (tries == 10)
{
System.out.println("Your guesses were incorrect");
System.out.print("You guessed: ");
for ( int i = 0; i < 10 ; i++)
{
System.out.print(guesses[i] + ", ");
}
System.out.println("The random number generated was " + number);
}
else
{
System.out.println("Well done! You were able to guess the "
+ "correct number in under 10 tries");
System.out.print("You guessed: ");
for ( int i = 0; i < tries; i++)
{
System.out.print(guesses[i] + " ");
}
System.out.println("The random number generated was "
+ number + ", it only took you " + tries + " tries.");
}
System.out.println("");
System.out.print("Do you wish to try again with a different "
+ "number? (Enter y or n ): ");
again = input.next();
System.out.println("");
}
}
/*
METHOD 1
Description
A method that generates the random number to be guessed returns the
random number to main. Two parameters are the two numbers needed to generate
the random number (1 and 100 in this case).
*/
public static int GetRandomNumber (int rangeLow, int rangeHigh)
{
Random gen = new Random();
int number;
number = gen.nextInt(rangeHigh) + rangeLow;
return number;
}
/*
METHOD 2
This method tells the user if the guess is too low or too high. It will have
2 parameters one for the random number and the second is the user guess.
*/
public static void LowOrHigh (int number, int userGuess )
{
if (userGuess > number )
{
System.out.println("The value that you guessed is too high, "
+"Try guessing a lower number. ");
System.out.println("");
}
else if (userGuess < number )
{
System.out.println("The value that you guessed is too low, "
+"Try guessing a higher number. ");
System.out.println("");
}
}
/*
METHOD 3
This method will get the user guess. It has 2 parameters which will be the
valid range the user should guess between (in this case 1 and 100). It will
return the users guess as an integer. This method should validate that the
users guess is between the two parameters.
*/
public static int GetUserGuess(int rangeLow, int rangeHigh)
{
Scanner scan = new Scanner(System.in);
int userGuess;
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
while (userGuess > rangeHigh || userGuess < rangeLow)
{
System.out.println("The number given was not within the range, Try again ");
System.out.println("");
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
}
return userGuess;
}
}
I'm sorry if its obvious im still pretty new to programming.

Whenever you store a guess, you always store it in guesses[tries], and then immediately afterwards, you increment tries. Your while condition then checks if tries is less than guess.length - 1.
More generally, to program you need to know how to debug. Debugging is generally the act of following along with the code and checking what it actually does vs. what you wanted it to do. You can use a debugger for this, alternatively, you can add a boatload of System.out statements to follow along.
Do that, and you'll find the error in your logic. I've already given you quite a sizable hint in the first paragraph ;)

Related

How to get guesses randomly generated

I am somewhat new to Java still and have a lab that needs to simulate a lottery game that generates a number between 1-10. It first asks the user how many tickets do they want to purchase and then asks them if they want the computer to generate the guesses for them, if yes then it will generate the guesses and reveal the winning numbers. If the user says no, then the user will input the guesses themselves and will show the winning numbers.
I am having a problem figuring out how to do the code for when someone enters yes or no. Should I do a do while loop?
Here is what I have as code right now.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double TICKET_PRICE = 2.00;
System.out.println("Welcome to the State of Florida Play10 Lottery Game. Ticket Price: $" + TICKET_PRICE);
System.out.println("How many tickets would you like to purchase?");
int ticketsPurchased = input.nextInt();
System.out.print("Please enter " + (ticketsPurchased) + " to confirm your credit carde charge: ");
int creditCardCharge = input.nextInt();
if (ticketsPurchased != creditCardCharge) {
System.out.println("Wrong number, please enter again: ");
return;
}
if (ticketsPurchased == creditCardCharge) {
System.out.println("Thank you. Your credit card will be charged $" + (ticketsPurchased * 2));
}
int min = 1;
int max = 10;
int winner;
winner = min + (int)(Math.random() * ((max - min) + 1));
System.out.print("Would you like the computer to generate your guesses? Enter 'Y' or 'N': ");
String computerGeneratedGuess = input.nextLine();
int guess = 0;
int winCtr = 0;
String output = "";
}
Here is the algorithm:
1. Get number of tickets to purchase,
calculate and confirm credit card charge.
2. Generate random winning integer and
either generate random guesses or prompt
user for guesses.
3. Report the winning number, the winning
tickets, total winnings, total losses, and
allowable deduction
Here is the lab its self:
Lab05 Lottery game
Generally a boolean is convenient to control a loop like this. Something like:
boolean gameOver = false;
int theGuess = 0;
while (!gameOver) {
if (computerGeneratedGuess == 'Y') {
theGuess = //code to generate a random number
}
else {
theGuess = //code to for user to enter a guess
}
if (theGuess == winner) {
gameOver = true;
}

Why does my code exit and not accept the "yes" pulled in with a Scanner or the one hardcoded in? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
It looks like the Scanner is being used correctly here and being assigned to a variable correctly but I Cannot figure out what is going on. When I play this game in the code, the INT gets pulled in just fine. The strings will not get pulled in for some reason and even if I hardcode "yes" for the string it still exits the code.
package testTraining;
import java.util.Scanner;
public class GuessingGame {
static int gamesPlayed; // The number of games played.
static int gamesWon; // The number of games won.
public static void main(String[] args) {
gamesPlayed = 0;
gamesWon = 0; // This is actually redundant, since 0 is
// the default initial value.
System.out.println("Let's play a game. I'll pick a number between");
System.out.println("1 and 100, and you try to guess it.");
String yesno = "yes";
Scanner yesScan = new Scanner(System.in);
do {
playGame(); // call subroutine to play one game
System.out.print("Would you like to play again? ");
yesno = yesScan.next();
} while (yesno == "yes");
System.out.println();
System.out.println("You played " + gamesPlayed + " games,");
System.out.println("and you won " + gamesWon + " of those games.");
System.out.println("Thanks for playing. Goodbye.");
} // end of main()
static void playGame() {
Scanner guessScan = new Scanner(System.in);
int computersNumber; // A random number picked by the computer.
int usersGuess; // A number entered by user as a guess.
int guessCount; // Number of guesses the user has made.
gamesPlayed++; // Count this game.
computersNumber = (int)(100 * Math.random()) + 1;
// The value assigned to computersNumber is a randomly
// chosen integer between 1 and 100, inclusive.
guessCount = 0;
System.out.println();
System.out.print("What is your first guess? ");
while (true) {
usersGuess = guessScan.nextInt(); // Get the user's guess.
guessCount++;
if (usersGuess == computersNumber) {
System.out.println("You got it in " + guessCount
+ " guesses! My number was " + computersNumber);
gamesWon++; // Count this win.
break; // The game is over; the user has won.
}
if (guessCount == 6) {
System.out.println("You didn't get the number in 6 guesses.");
System.out.println("You lose. My number was " + computersNumber);
break; // The game is over; the user has lost.
}
// If we get to this point, the game continues.
// Tell the user if the guess was too high or too low.
if (usersGuess < computersNumber)
System.out.print("That's too low. Try again: ");
else if (usersGuess > computersNumber)
System.out.print("That's too high. Try again: ");
}
System.out.println();
} // end of playGame()
} // end of class GuessingGame
You need to compare strings with .equals("yes") instead of == "yes"

Why does the second while loop cancel both while loops?

Why does the second while loop while (numberOfTries < 2) cancel both while loops? It runs perfect if there is no incorrect answer. But let's say I select 4 problems to be made, and I am only on the first problem. I give the incorrect answer 2 times so the program should say Incorrect two times and then give me a new question because while (numberOfTries < 2) should force it to break from that loop. But it doesn't, it just quits the whole thing. I know it has to be a logic issue, so what am I missing?
import java.util.Random;
import java.util.Scanner;
public class Howthe {
public static void main(String[] args) {
// Open Scanner
Scanner scan = new Scanner(System.in);
// Ask user to choose number of problems to be made.
// Can only choose 4, 9, or 16
System.out.print("Choose a number of problems to be made (4, 9, 16): ");
int userChoiceOfProblems = scan.nextInt();
// Ask user to choose a number between 0 and 12
System.out.print("\nChoose a number between 0 and 12: ");
int userNumberBetween0and12 = scan.nextInt();
// Ask user to choose between add/sub or multiply/divide
System.out.println("\nChoose to:"
+ "\n0: add/sub your chosen number"
+ " and the randomly generated number: "
+ "\n1: multiply/divide your chosen number"
+ " and the randomly generated number: ");
int userArithmeticChoice = scan.nextInt();
int counter = 0;
String equationString;
int equationAnswer;
int numberOfAnswersRight = 0;
int numberOfTries = 0;
int userAnswerToQuestion;
if (userArithmeticChoice == 0){
while (counter < userChoiceOfProblems){
// Create random number to decide if add or sub used.
// add is equal to 0 and sub is equal to 1
Random rand = new Random();
int randomNumberBetween0and1 = rand.nextInt(1) + 0;
// Create random number that is multiplied by userNumberBetween0and12
int randomNumberBetween0and12 = rand.nextInt(12) + 0;
// Add and increase counter by 1
if (randomNumberBetween0and1 == 0){
// If numberOfTries is more than 2, then display answer.
while (numberOfTries < 2){
// Compute the right answer (addition).
equationAnswer = userNumberBetween0and12 + randomNumberBetween0and12;
// Produce string of equation, then display string (addition).
equationString = userNumberBetween0and12 + " + "
+ randomNumberBetween0and12;
System.out.println(equationString);
userAnswerToQuestion = scan.nextInt();
// If answer is right, increase numberOfAnswersRight.
if (userAnswerToQuestion == equationAnswer){
numberOfAnswersRight++;
System.out.println("Correct!");
break;
}
// If answer is wrong, continue loop and increase numberOfTries
else if (userAnswerToQuestion != equationAnswer){
numberOfTries++;
System.out.println("Incorrect");
}
} // end of while (numberOfTries < 2 && !quit)
counter++;
}
} System.out.println("Yout got " + numberOfAnswersRight + " problem(s) right!");
}
}
}
numberOfTries is initialized outside of your loops. Once you try twice, it never gets set back to 0 which causes the loops to skip and finish on the next question because numberOfTries is already 2.

How do i fix this simple program? guessing game

Hello please please please can someone help me. I am writing a program where the user can enter a maximum number for a guessing game and using a random generator he/she would have to guess the number from 1-to the max number. i have done most of it but i am stuck on how to loop back the program to enter another input if user say enters a letter or anything else apart from an integer. From the "do" part is where i get confused!
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class guessinggame { // class name
public static void main(String[] args) { // main method
String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
int max = Integer.parseInt(smax);
do {
if (max > 10000) {
JOptionPane.showMessageDialog(null, "Oh no! keep your choice below 10000 please.");
smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
max = Integer.parseInt(smax);
}
} while (max > 10000);
int answer, guess = 0, lowcount = 0, highcount = 0, game;
String sguess;
Random generator = new Random();
answer = generator.nextInt(max) + 1;
ArrayList<String> buttonChoices = new ArrayList<String>(); // list of string arrays called buttonChoices
buttonChoices.add("1-" + max + " Guessing Game");
Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons
game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
null, buttons, buttonChoices.get(0));
do {
sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
try {
guess = Integer.parseInt(sguess);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
break;
} while (guess != answer);
JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
+ "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");
System.exit(0);
}
}
First thing's first, the break in the last do-while. If you break without condition inside a loop; it's not a loop; it's a single-execution block.
Other than that, you should, in areas where you're validating input, follow this structure. (pseudo code so you can implement).
Do-While input does not equal answer
Get input from user with dialogue
Begin Try
Parse user input
If input > answer
Notify user
Else-If input < answer
Notify user
End Try
Begin Catch Parse error
Alert user of invalid input
End Catch
End While

Calling local variables in other static methods?

I am supposed to write a program that selects a random number between user given constraints, and asks the user to input guesses as to what this number is. The program gives feedback to the user as to whether or not the number is higher or lower than the user's guesses. The number of guesses, the number of games, the total guesses used throughout all of the games, and the lowest number of guesses used in one game are recorded.
These results are printed. The functions that responsible for running the game (playGame()) and the functions responsible for printing these results (getGameResults()) must be in two separate methods.
My problem is, I am not sure how to get the local variables that are modified throughout the course of the method playGame() to the getGameResults() method.
getGameResults() is intended to be called in another method, continuePlayTest(), which tests the user's input to determine whether or not they wish to continue playing the game, so I don't think that calling getGameResults() will work, otherwise this test will not work either. Unless I call continuePlayTest() in playGame(), but continuePlayTest() calls playGame() in its code so that would complicate things.
We can use ONLY the concepts that we've learned. We cannot use any concepts ahead.
So far, we've learned how to use static methods, for loops, while loops, if/else statements and variables. Global variables are bad style, so they cannot be used.
CODE:
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean whileTest = false;
gameIntroduction();
Scanner console = new Scanner(System.in);
playGame(console);
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
//Takes the user's input and compares it to a randomly selected number.
public static void playGame(Scanner console) {
int guesses = 0;
boolean playTest = false;
boolean gameTest = false;
int lastGameGuesses = guesses;
int numberGuess = 0;
int totalGuesses = 0;
int bestGame = 0;
int games = 0;
guesses = 0;
games++;
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
Random number = new Random();
int randomNumber = number.nextInt(MAXIMUM) + 1;
while (!(gameTest)){
System.out.print("Your guess? ");
numberGuess = console.nextInt();
guesses++;
if (randomNumber < numberGuess){
System.out.println("It's lower.");
} else if (randomNumber > numberGuess){
System.out.println("It's higher.");
} else {
gameTest = true;
}
bestGame = guesses;
if (guesses < lastGameGuesses) {
bestGame = guesses;
}
}
System.out.println("You got it right in " + guesses + " guesses");
totalGuesses += guesses;
continueTest(playTest, console, games, totalGuesses, guesses, bestGame);
}
public static void continueTest(boolean test, Scanner console, int games, int totalGuesses, int guesses, int bestGame) {
while (!(test)){
System.out.print("Do you want to play again? ");
String inputTest = (console.next()).toUpperCase();
if (inputTest.contains("Y")){
playGame(console);
} else if (inputTest.contains("N")){
test = true;
}
}
getGameResults(games, totalGuesses, guesses, bestGame);
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
System.out.println("Overall results:");
System.out.println("\ttotal games = " + games);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double)Math.round(guesses/games) * 100)/100);
System.out.println("\tbest game = " + bestGame);
}
}
If you cannot use "global" variables, I guess your only option is passing parameters when calling the method. If you don't know how to declare and use methods with parameters, I don't know another answer.
EDIT/ADD
After you specified your question, circumstances and posted your code I got a working solution including comments.
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean play = true; // true while we want to play, gets false when we quit
int totalGuesses = 0; // how many guesses at all
int bestGame = Integer.MAX_VALUE; // the best games gets the maximum value. so every game would be better than this
int totalGames = 0; // how many games played in total
Scanner console = new Scanner(System.in); // our scanner which we pass
gameIntroduction(); // show the instructions
while (play) { // while we want to play
int lastGame = playGame(console); // run playGame(console) which returns the guesses needed in that round
totalGames++; // We played a game, so we increase our counter
if (lastGame < bestGame) bestGame = lastGame; // if we needed less guesses last round than in our best game we have a new bestgame
totalGuesses += lastGame; // our last guesses are added to totalGuesses (totalGuesses += lastGame equals totalGuesses + totalGuesses + lastGame)
play = checkPlayNextGame(console); // play saves if we want to play another round or not, whats "calculated" and returned by checkPlayNextGame(console)
}
getGameResults(totalGames, totalGuesses, bestGame); // print our final results when we are done
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
// Takes the user's input and compares it to a randomly selected number.
public static int playGame(Scanner console) {
int guesses = 0; // how many guesses we needed
int guess = 0; // make it zero, so it cant be automatic correct
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
int randomNumber = (int) (Math.random() * MAXIMUM + 1); // make our random number. we don't need the Random class with its object for that task
while (guess != randomNumber) { // while the guess isnt the random number we ask for new guesses
System.out.print("Your guess? ");
guess = console.nextInt(); // read the guess
guesses++; // increase guesses
// check if the guess is lower or higher than the number
if (randomNumber < guess)
System.out.println("It's lower.");
else if (randomNumber > guess)
System.out.println("It's higher.");
}
System.out.println("You got it right in " + guesses + " guesses"); // Say how much guesses we needed
return guesses; // this round is over, we return the number of guesses needed
}
public static boolean checkPlayNextGame(Scanner console) {
// check if we want to play another round
System.out.print("Do you want to play again? ");
String input = (console.next()).toUpperCase(); // read the input
if (input.contains("Y")) return true; // if the input contains Y return true: we want play another round (hint: don't use contains. use equals("yes") for example)
else return false; // otherwise return false: we finished and dont want to play another round
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int totalGames, int totalGuesses, int bestGame) {
// here you passed the total guesses twice. that isnt necessary.
System.out.println("Overall results:");
System.out.println("\ttotal games = " + totalGames);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double) (totalGuesses) / (double) (totalGames))); // cast the numbers to double to get a double result. not the best way, but it works :D
System.out.println("\tbest game = " + bestGame);
}
}
Hope I could help.
Is it a problem passing the variables between functions? ex:
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
// implementation
}
Another option, assuming this is all in one class, is using private static memeber variables. They aren't global. Then again, they might be considered 'global' by your teacher for this assignment.
Given that you've only learnt how to use static methods, your only option is to pass the information from function to function via its arguments.

Categories

Resources