Problem with keeping score with a while loop (Java) - java

I am in an intro to the java class, and for one of my assignments, I have to use a loop (for or while) to keep track of scores between myself and the computer.
Here is the exact word for word instructions from my professor:
Write a program that does this: You (as a programmer) are the dealer.
pick a random number for yourself (between 0 - 100). Ask the user to input a random number (between 0 - 100) Whoever is closer to 21 wins the game.
(part 2) -Loop (keeping a counter) rite the same program and keep it going so that it keeps playing (dealing hands and saying who wins) until the user enters 21 at which point you print out some stats and say goodbye. For example, your goodbye might look like this:
Number of rounds played: 5
Dealer won: 3
Player won:2
you're 2 for 5.
Now I have written the code and played around it for hours and hours, and cannot make it work with a loop. I've tried while, do while, and for. I have looked everywhere on the internet for similar examples but cannot make a loop work in my program whatsoever. If anyone has any suggestions I would sure appreciate the feedback.
my code:
import java.util.*;
class asd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
System.out.println("computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("the winner is the user!" + input);
dealerscore++;
gamesplayed++;
} else {
System.out.println("the winner is the computer!" + r);
userscore++;
gamesplayed++;
}
if (input == c) {
System.out.println("thank you for playing. you won.");
}
if (r == c) {
System.out.println("Thank you for playing:" + userscore);
System.out.println(userscore);
}
if (input == 0) {
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
while (input != c && r != c)
gamesplayed++;
}
// TODO code application logic here
}
Everything works fine, but I can't get the loop to work anywhere here.

You need a while loop that contains your game logic. The condition should just check if the input != c.
Then inside the loop, keep asking the user for input. Also, you mixed up userscore and dealerscore when adding the score.
Then at the end, once you come out of the loop, you can print the scores/stats.
Please read the comments below:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!: ");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
/*
This loop runs the game until the user enters 21
*/
while (input != c) {
System.out.println("Computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user! " + input);
userscore++; //You mixed up userscore and dealerscore
} else {
System.out.println("The winner is the computer! " + r);
dealerscore++; //You mixed up userscore and dealerscore
}
/*
User needs to keep entering guesses
*/
System.out.println();
System.out.println("Enter another guess: ");
r = rand.nextInt(max - min) + min;
input = sc.nextInt();
}
/*
You don't need any conditions since the games have already ended
But it should be outside and after the loop
*/
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
}

Change the loop with
while (input != c && r != c){
gamesplayed++;
System.out.println("Games played: " + gamesplayed );
}
you will see it is working. I would format the code better to debug it easier and always use the brackets.

Try this. Just refer to the code for explanations.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
System.out.println("");
int min = 0;
int max = 100;
int input;
int c = 21;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 1;
Random rand = new Random();
while (true) { // so that the game will keep playing
System.out.println("----------------- ROUND " + gamesplayed + " -----------------");
int r = rand.nextInt(max - min) + min; // computer's choice
while (true) { // so that it will keep asking the user in case the user enters an invalid input
try {
System.out.print("Enter a random number! :");
input = Integer.parseInt(sc.nextLine());
break;
} catch (Exception e) {
System.out.println("Invalid input!");
}
}
System.out.println("The computer's random number is " + r);
// checking for the rounds winner
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user!");
userscore++;
} else {
System.out.println("The winner is the computer!");
dealerscore++;
}
if (input == c) { // checking for ending the game
System.out.println("================ GAME STATS ================");
System.out.println("Thank you for playing.");
System.out.println("Number of hands played: " + gamesplayed);
System.out.println("Dealer score: " + dealerscore);
System.out.println("User score: " + userscore);
System.out.println("You are " + userscore + " out of " + gamesplayed + "!");
System.out.println("============================================");
sc.close();
break;
}
gamesplayed++; // increment games played
System.out.println("--------------------------------------------");
}
}
}

Related

Having trouble w/ returning and passing values; "counting"

Our task was to create a guessing game, where the computer would generate a number and the user was prompted to guess. We were to create a method to play only one game, and then create a while loop in the main to make the game playable again. In the end, we need to show statistics. I'm having trouble with showing the "best game." That is a game where the amount of guesses is the least.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
// This is the main. Here we can see a do/while loop
// and a few variables that were created to compliment it.
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
do {
totalGuess = game(console);
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
statistics(totalGames, totalGuess);
}
// This method prints out the intro.
public static void intro() {
System.out.println("This program allows you to play a guessing
game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAX + " 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.\n ");
}
// This method plays the game only once. It's later used in the main.
// Returns the
// number of guesses for one game.
public static int game(Scanner console) {
Random rand = new Random();
int random = rand.nextInt(MAX) + 1;
System.out.println("I'm thinking of a number between 1 and " + MAX + "
... (it's " + random + " )");
System.out.print("Your guess? > ");
int guess = console.nextInt();
int count = 0;
do {
if ((random - guess) > 0) {
System.out.println("It's higher.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if ((random - guess) < 0) {
System.out.println("It's lower.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if (random == guess) {
count++;
}
} while (random != guess);
if (count == 1) {
System.out.println("You got it right on the first guess!!");
}
else {
System.out.println("You got it right in " + count + " guesses.");
}
return count;
}
// This method prints out the statistics.
public static void statistics(int x, int y) {
System.out.println("total games = " + x);
System.out.println("total guesses = " + (y));
System.out.println("guesses/game = ");
System.out.println("best game = ");
}
}
Have a look when totalGuess is assigned:
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
// ^ Initialized to zero
do {
totalGuess = game(console);
// ^ Assigned (not added) to the return value from game.
// Did you mean: totalGuess += game(console); ?
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
// ^ Assigned to itself. No action.
statistics(totalGames, totalGuess);
}

error msgs after second loop attempt

I'm working on another assignment and am stuck. First off, I realize I probably won't get the results I want from this code, but at the moment I can't run the code to even see how close or far away I am. I'm sure I'm missing something simple and hope that something will pop out to someone here so I can move past this point. My mother tongue is English but I'm living in Sweden and trying to learn code in a Swedish class so I added //for translations.
Again, I am working with very basic code so am not looking for an easy hack, more of just some insight to where I have gone wrong.
My assignment is to ask the user to enter 10 numbers, store those as an array. Then, offer the user 4 options to calculate those numbers and a 5th option to quit the program.
Here's what I have so far:
package inlämningsuppgift3;
import java.util.Scanner;
import java.util.Arrays;
public class Inlämningsuppgift3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal = 0;
int[] num = new int[10];
int sum = 0;
int min = 0;
int max = 0;
for (nr = 0; nr < 10; nr++) {
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr] = tal;
if (nr == 0) { //first number
min = tal;
max = tal;
}
else { // All other numbers
if (tal > max) { max = tal; }
if (tal < min) { min = tal; }
}
sum = sum + tal;
}
{
// What would you like to do?
System.out.println("Välj vad du vill göra?");
// Show largest number
System.out.println("1: Visa storsta talet.");
// Show smallest number
System.out.println("2: Visa minsta talet.");
// Show average
System.out.println("3: Visa medeltalet.");
// Show all numbers
System.out.println("4: Visa alla inmatade tal.");
// Quit
System.out.println("5: Avsluta");
}
do {
int k = input.nextInt();
if (k == 1) {
// Largest number is:
System.out.println("Storsta talet är: " + max);
}
else if (k == 2) {
// Smallest number is:
System.out.println("Minsta talet är: " + min);
}
else if (k == 3) {
// Average number is:
System.out.println("Medeltalet är: " + sum/10);
}
else if (k == 4) {
// All the entered numbers:
System.out.println("Alla tal: " + num[10] + ", ");
}
else if (k==5) {
// Goodbye
System.out.println("Hej då!");
break;
}
else {
System.out.println("Felaktigt, prova igen.");
// Unrecognized, try again.
}
while (k<5);
}
}
}
I'm getting error on the last 3 } and I'm not sure why. Are they in the wrong place? I've tried moving them around, I've tried deleting them (obviously, didn't help either) I tried changes to my {} placement above in the code and just haven't found a way around this error. Thank you in advance for any input!
java do-while syntax is:
do {
// Statements
}while(Boolean_expression);
so, change it to:
int k = 0;
do {
k = input.nextInt();
if (k == 1) {
System.out.println("Storsta talet är: " + max);
} else if (k == 2) {
System.out.println("Minsta talet är: " + min);
} else if (k == 3) {
System.out.println("Medeltalet är: " + sum / 10);
} else if (k == 4) {
System.out.println("Alla tal: " + num[10] + ", ");
} else if (k == 5) {
System.out.println("Hej då!");//good bye
break;
} else {
System.out.println("Felaktigt, prova igen.");
}
} while (k < 5) ;
and after while line must be two } now.
Hej Hej!
I made the modifications I think like you asked to make it 'just about work'
package Dunno;
import java.util.Scanner;
public class NumberCollector { //No special characters in source files,
//Can get transformed during deployment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal =0;
int[] num = new int[10];
int sum = 0;
int min=0;
int max=0;
for (nr=0; nr<10; nr++)
{
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr]=tal;
if(nr == 0) //first number
{
min=tal;
max=tal;
}
else //all other numbers
{
if(tal>max)max =tal;
if(tal<min) min=tal;
}
sum = sum + tal;
}
System.out.println("Välj vad du vill göra?");
//what would you like to do?
System.out.println("1: Visa storsta talet.");
//Show largest number
System.out.println("2: Visa minsta talet.");
//show smallest number
System.out.println("3: Visa medeltalet.");//show average
System.out.println("4: Visa alla inmatade tal.");
//show all numbers
System.out.println("5: Avsluta");//quit
while (true) //Moved the stop condition to start of the loop makes it easier to read logically.
{
int k = input.nextInt();
if (k==1)
{
System.out.println("Storsta talet är: " + max);
//largest number is:
}
else if (k==2)
{
System.out.println("Minsta talet är: " + min);
//smallest number is:
}
else if (k==3)
{
System.out.println("Medeltalet är: " + sum/10);
//average number is:
}
else if (k==4)
{
System.out.println("Alla tal: " + num[10] + ", ");
//all the entered numbers:
}
else if (k==5)
{
System.out.println("Hej då!");//good bye
break;
}
else
{
System.out.println("Felaktigt, prova igen.");
//unrecognized, try again.
}
};
}
}
I only had to move around some braces.
It seems to broadly do what you want? It throws an exception if you ask for result 4, I'll leave that to you :)
Maybe this will be a good starting point? Consider replacing the loop with a switch/case condition would be nicer to read and maintain?

Java Guessing Game count total guesses

so I am having trouble with being able to have a proper TOTAL guess counter.
My code needs to be basic so please dont offer me advice for doing anything you think is not trivial.
Currently,
my code plays a game, then asks the user if they want to play again and its a simple Y or N.
If yes, another games plays
If no then then game ends and it reports the results of every game played as such: the total games, guesses per game, and the best game (reports game that had lowest guess count).
My issues are being able to accurately count ALL THE GUESSES from every game. I am able to report results and track the total games played correctly but I can't figure out how to report a result that tracks the guesses per game, adds them all up, finds the smallest one.
import java.util.*;
public class GuessingGame {
public static final int MAX = 100;
public static void main(String[] args) {
Scanner console = new Scanner(System.in); //to use scanner
Random r = new Random(); //to use random numbers
intro();
int totalGuesses = guess(console, r);
System.out.print("Do you want to play again? ");
String answer = console.next();
int plays = 1;
//while loop reads user input and determines wether
//or not to play the game again
while(answer.charAt(0) == 'y' || answer.charAt(0) == 'Y') {
System.out.println();
guess(console, r);
System.out.print("Do you want to play again? ");
answer = console.next();
plays++;
}
System.out.println();
results(plays, totalGuesses);
}
}
//method that creates the guessing game and congratulatory message
public static int guess(Scanner console, Random r) {
System.out.println("I'm thinking of a number between one and " + MAX + "...");
int theNumber = 50; //creates a random answer between one and the MAX class constant
int userGuess = 0;//establishes the integer for the user's guess
int guesses = 0; //establishes the amount of guesses
int totalGuesses = 0;
while(userGuess != theNumber) { //while loop that executes until answer is correct
System.out.print("Your guess? ");
userGuess = console.nextInt();
if(userGuess > theNumber) {
System.out.println("It's lower.");
} else if (userGuess < theNumber) {
System.out.println("It's higher.");
}
guesses++;
}
if(guesses == 1) {
System.out.println("You got it right in 1 guess!");
} else {
System.out.println("You got it right in " + guesses + " guesses!");
}
totalGuesses += guesses;
return totalGuesses;
}
//prints out the stats of the game
public static void results(int plays, int totalGuesses) {
System.out.println("Overall results:");
System.out.println("Total games = " + plays);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = ");
System.out.println("Best game = ");
}
}
Your variable called "guesses" must be created in the main class, not inside the guess method.
Then, just add it to the method ( public static int guess (scanner,random,int guesses))
Your variables guesses and totalGuesses needs to be instantiated outside of the method. Put int guesses and int totalGuesses just above
public static int guess(Scanner console, Random r) {
System.out.println("I'm thinking of a number between one and " + MAX + "...");
so that it is like this
int guesses = 0;
int totalGuesses = 0;
public static int guess(Scanner console, Random r) {
System.out.println("I'm thinking of a number between one and " + MAX + "...");
and remove them from inside of the class so that its like this.
int userGuess = 0;//establishes the integer for the user's guess
while(userGuess != theNumber)
You should also add guesses = 0; in the main class here.
System.out.print("Do you want to play again? ");
answer = console.next();
plays++;
guesses = 0;
}
Here's the whole code in one main method. Maybe it'll shed some light.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
int MAX = 100; //ceiling for the random number
int total = 0; //total number of guess
int plays = 0; //total number of games
int bestGame = Integer.MAX_VALUE; //used to determine game with lowest amount of guesses
String answer; //holds user input
boolean playing = true; //used to determine if the game is ongoing
while (playing) { //while game is ongoing
System.out.println("I'm thinking of a number between one and " + MAX + "...");
int theNumber = r.nextInt(MAX) + 1; //generate random int [1, 100]
int userGuess = 0; //holds user guess
int guesses = 0; //total number of guesses this game
while(userGuess != theNumber) { //while number is not guessed
System.out.print("Your guess?\n");
userGuess = console.nextInt();
if (userGuess > theNumber) System.out.println("It's lower.");
else if (userGuess < theNumber) System.out.println("It's higher.");
guesses++; //increase guesses this round by 1
}
if (guesses < bestGame) bestGame = guesses; //if we used less guesses than in our best game this is our new best game
System.out.println("You got it right in " + guesses + " guess(es)!");
plays++; //increase number of games by 1
total += guesses; //increase total guesses by guesses this round
System.out.println("Again?");
answer = console.next();
if (answer.toLowerCase().equals("n")) playing = false; //if input is n (or N) we exit the loop
}
console.close(); //close scanner
System.out.println("Overall results:"); //print results
System.out.println("Total games = " + plays);
System.out.println("Total guesses = " + total);
System.out.printf("Guesses/game = %.2f%n", (double) total/plays); //cast to double to prevent integer division
System.out.println("Best game = " + bestGame);
}

Creating 1 decimal place

So I am more or less completely done with this code that runs a guessing game. At the end it prints the total results for all games played. This includes total games, total guesses, avg guesses/game and the best score. I have it all worked out except i need the avg guesses/game to show 1 decimal place but the System.out.printf("Guesses/game = %.1f") isn't working and idk why
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
int bestGame = Integer.MAX_VALUE;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) { //repeats until user enters a statement besides y when asked to play again
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
bestGame = Math.min(bestGame, numberOfTries);
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.printf("Guesses/game = ", totalGuesses/totalGames);
System.out.println("Best game = " + bestGame);
}
}
both totalGuesses and totalGames are integers, so when you divide them you get an integer, whereas %f needs a floating point number.
Instead cast one to a floating point number for floating point division:
totalGuesses/(double)totalGames
Try a decimal formatter if for some reason you're simply getting the wrong output:
DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(avgGuesses)); //or whatever your var name is

How to add the "play again?" feature for java

Im making a guessing game for my class and I need some help for adding a "play again" feature at the end of the game when you've guessed the right number:
public class GuessingGame
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
while (guess != numtoguesses)
{
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
}
}
One simple approach would be to move the code you've written into a function
public void play() {
...
}
and from main do something like:
do {
play();
playAgain = promptUser;
} while(playAgain);
Just put another while loop over everything.
boolean playing = true;
while(playing) {
while(guess != numtoguesses) { // All code }
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
}
Everything together:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
boolean playing = true;
while(playing) {
while (guess != numtoguesses) {
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
numtoguesses = rand.nextInt(1000) + 1;
}
You should extract this in a few methods, but I'll leave that up to you.
There are a lot of options I can think about. The quickest:
-- place all the code between lines int numtoguesses = rand.nextInt(1000) + 1; (inclusive) and end of main method inside an infinite loop
-- at the end of your current code block, add an interogation to the user, asking him whether he/she wants to play again (you can define a convention for the pressed keys); this part is placed also inside the infinite loop
-- if he/she doesn't want to, break the (outer) infinite loop

Categories

Resources