Basically this program roles a dice between a computer and then shows who got the higher score. So in my last if/else statement, the main difference is you won, vs you lost. Is there anyway that I can combine this so it's cleaner? I tried combining it but couldn't figure it out. Any ideas? Appreciate it!!
//import scanner and random
import java.util.Random;
import java.util.Scanner;
//declare variables and methods
class Main {
int userOne, userTwo, compOne, compTwo, userTotal, compTotal;
char playAgain;
Scanner scan = new Scanner(System.in);
Random gen = new Random();
//method to run entire program
public void runProgram()
{
int r=1;
//this will run the roll of the dice for the user and the computer
for(r=1; r<2;)
{
System.out.println("Your turn:");
userOne = gen.nextInt(6)+1;
System.out.println("Your first roll was: " + userOne);
userTwo = gen.nextInt(6)+1;
System.out.println("Your second roll was: " + userTwo);
userTotal = userOne + userTwo;
System.out.println("Your total of the two rolls was: " + userTotal);
System.out.println("Computers turn:");
compOne = gen.nextInt(6)+1;
System.out.println("The computers first roll was: " + compOne);
compTwo = gen.nextInt(6)+1;
System.out.println("The computers second roll was: " + compTwo);
compTotal = compOne + compTwo;
System.out.println("The computers total of the two rolls was: " + compTotal);
//This determines win or loss and lets the user choose if they want to play again
if (userTotal > compTotal)
{
//winning- statement to ask if the user wants to play again
System.out.println("You won! Would you like to play again? Respond with Yes or No: ");
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y") == true)
{
r=1;
}
else
{
r=2;
}
}
else
{
//losing- statement to ask if the user wants to play again
System.out.println("Sorry, you lost. Would you like to play again? Yes or No?");
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y") == true)
{
r=1;
}
else
{
r=2;
}
}
}
}
public static void main(String[] args) {
Main prog = new Main();
prog.runProgram();
}
}
Yes, by moving the code responsible for determining whether or not to run the program again outside the if/else statement since it doesn't matter if the user won or lost, in the end, the question remains the same: do you want to play again or not? regardless of the result, therefore such logic should not be encapsulated by the logic responsible for determining who one (because again, irrelevant).
The second thing and this is totally optional but it will make your code cleaner, it seems you're using if/else statements just to determine which values should be assigned to variables, in such cases, it is cleaner to use the ternary operator
And one more thing, when using methods that return a boolean true/false it is unnecessary to type == false/true since the function itself already does that, such as the equalsIgnoreCase() function.
So after all of these edits, your code looks something like this:
//import scanner and random
import java.util.Random;
import java.util.Scanner;
//declare variables and methods
class Main {
int userOne, userTwo, compOne, compTwo, userTotal, compTotal;
char playAgain;
Scanner scan = new Scanner(System.in);
Random gen = new Random();
String result;
//method to run entire program
public void runProgram() {
int r=1;
//this will run the roll of the dice for the user and the computer
for(r=1; r<2;)
{
System.out.println("Your turn:");
userOne = gen.nextInt(6)+1;
System.out.println("Your first roll was: " + userOne);
userTwo = gen.nextInt(6)+1;
System.out.println("Your second roll was: " + userTwo);
userTotal = userOne + userTwo;
System.out.println("Your total of the two rolls was: " + userTotal);
System.out.println("Computers turn:");
compOne = gen.nextInt(6)+1;
System.out.println("The computers first roll was: " + compOne);
compTwo = gen.nextInt(6)+1;
System.out.println("The computers second roll was: " + compTwo);
compTotal = compOne + compTwo;
System.out.println("The computers total of the two rolls was: " + compTotal);
//This determines win or loss and lets the user choose if they want to play again
result = userTotal > compTotal ? "won! " : "lost. ";
// Ternary operator
System.out.println("you " + result + "Would you like to play again? Yes or No?");
playAgain = scan.next().charAt(0);
// another ternary operator
r = String.valueOf(playAgain).equalsIgnoreCase("y") ? 1 : 2;
}
}
public static void main(String[] args) {
Main prog = new Main();
prog.runProgram();
}
}
Like khelwood suggested, you can combine the play again messages outside of the win/loss if statement.
if (userTotal > compTotal) {
System.out.println("You won!");
} else {
System.out.println("Sorry, you lost.");
}
System.out.println("Would you like to play again? Yes or No?");
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y")) {
r = 1;
} else {
r = 2;
}
One thing that I would say could be improved with this code is avoiding copying and pasting code. Don't ever repeat yourself.
Second thing to improve is you could make your loop while((String.valueOf(playAgain)).equalsIgnoreCase("y")) instead of your weird for loop. That way you don't have a confusing r variable that is based on whether or not playAgain is 'y'.
public void runProgram()
{
playAgain = 'y';
//this will run the roll of the dice for the user and the computer
while ((String.valueOf(playAgain)).equalsIgnoreCase("y") == true)
{
System.out.println("Your turn:");
userOne = gen.nextInt(6)+1;
System.out.println("Your first roll was: " + userOne);
userTwo = gen.nextInt(6)+1;
System.out.println("Your second roll was: " + userTwo);
userTotal = userOne + userTwo;
System.out.println("Your total of the two rolls was: " + userTotal);
System.out.println("Computers turn:");
compOne = gen.nextInt(6)+1;
System.out.println("The computers first roll was: " + compOne);
compTwo = gen.nextInt(6)+1;
System.out.println("The computers second roll was: " + compTwo);
compTotal = compOne + compTwo;
System.out.println("The computers total of the two rolls was: " + compTotal);
//This determines win or loss and lets the user choose if they want to play again
if (userTotal > compTotal)
{
//winning- statement to ask if the user wants to play again
System.out.println("You won! Would you like to play again? Respond with Yes or No: ");
}
else
{
//losing- statement to ask if the user wants to play again
System.out.println("Sorry, you lost. Would you like to play again? Yes or No?");
}
playAgain = scan.next().charAt(0);
}
}
Making these changes make your code a little more clear about what you're intending the program to do.
Just moves duplicated stuff out of the if-else statement.
Also, == true can be removed from if() since it already returns a boolean value.
if (userTotal > compTotal){
//winning- statement to ask if the user wants to play again
System.out.println("You won! Would you like to play again? Respond with Yes or No: ");
}else{
//losing- statement to ask if the user wants to play again
System.out.println("Sorry, you lost. Would you like to play again? Yes or No?");
}
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y")){
r=1;
}else{
r=2;
}
Related
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 ;)
It will only go through one time so it will end with "Would you like to make another request?(y/n)"
and when I input "y" it stops there and won't do the loop.
package Chaterp5PPReynaGuerra;
import java.util.*;
public class MeetingRequest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
final int CAPACITY=30;
String name;
int people;
int morePeople;
String answer="y";
int fewerPeople;
System.out.println("--------Meeting Request System"+
"--------");
System.out.println("\nWelcome to the Meeting Request System."+
" May I know your name?");
name=scan.nextLine();
while(answer.equalsIgnoreCase("y"))
{
System.out.println("Hello, "+name+", how many people"+
" will be attending the meeting?");
people=scan.nextInt();
morePeople = CAPACITY - people;
if(people < CAPACITY)
System.out.println("You can invite "+morePeople+
" more people to the meeting.");
else if(people > CAPACITY) {
fewerPeople= people - CAPACITY;
System.out.println("Sorry, the room is not "+
"big enough to seat that many people. You have to "+
"exclude "+fewerPeople+" from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another"+
" request?(y /n)");
// gets rid of \n in the input stream
scan.next();
answer=scan.nextLine();
}
}
}
Replace
people=scan.nextInt();
with
people = Integer.parseInt(scan.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Given below is the corrected program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int CAPACITY = 30;
String name;
int people = 0;
int morePeople;
String answer = "y";
int fewerPeople;
boolean valid;
System.out.println("--------Meeting Request System" + "--------");
System.out.println("\nWelcome to the Meeting Request System." + " May I know your name?");
name = scan.nextLine();
do {
do {
valid = true;
System.out.println("Hello, " + name + ", how many people" + " will be attending the meeting?");
try {
people = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid entry. Pleaase try again.");
valid = false;
}
} while (!valid);
morePeople = CAPACITY - people;
if (people < CAPACITY)
System.out.println("You can invite " + morePeople + " more people to the meeting.");
else if (people > CAPACITY) {
fewerPeople = people - CAPACITY;
System.out.println("Sorry, the room is not " + "big enough to seat that many people. You have to "
+ "exclude " + fewerPeople + " from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another" + " request?(y /n)");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
--------Meeting Request System--------
Welcome to the Meeting Request System. May I know your name?
abc
Hello, abc, how many people will be attending the meeting?
x
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
10.4
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
4
You can invite 26 more people to the meeting.
Would you like to make another request?(y /n)
y
Hello, abc, how many people will be attending the meeting?
5
You can invite 25 more people to the meeting.
Would you like to make another request?(y /n)
n
Some other important points:
As you can see, a do...while loop is more appropriate instead of while loop in this case.
You should always check for the NumberFormatException whenever you parse a text (e.g. Scanner::nextLine()) to integer.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
To get rid of the \n use scan.nextLine
// gets rid of \n in the input stream
scan.nextLine();
answer=scan.nextLine();
Hope this help.
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"
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
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.