I'm currently making a high-low guessing game in Java. I believe I have two issues hindering the game from functioning properly.
Firstly, I have a while-statement inside the playGame method that doesn't change as it is now, and I have trouble understanding how I can make it change if the correct guess is made. As I understand it I can't change the value of boolean bool = true; from the giveResponse method, it has to be done from the same method playGame? If there a better way of doing this than using a while-statement?
Secondly, when the correct guess is made and the playGame method return the value of parameter guessCount to the main method it should then be printed out. The instruction I have for this game says it should be printed in the main method after the return have been made.
import java.io.Reader;
import java.util.Scanner;
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r"
+ "1. 1-10 \r"
+ "2. 1-100 \r"
+ "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n==1) {
playGame(10);
}
else if (n==2) {
playGame(100);
}
else if (n==3) {
playGame(1000);
}
else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int)(Math.random() * maxNumber) +1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
giveResponse(answer, guess);
}
return guessCount;
}
public static void giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
}
else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
}
else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
}
}
}
I hope the questions are clear and specific enough. Any pointers in the right direction is appreciated.
You could have the giveResponse method return a boolean
static boolean giveResponse(...)
and put return false; inside the if (guess == answer){ case, and return true at the end of the method. Instead of calling giveResponse as a void method, use bool = giveResponse(answer,guess).
And for the second question, add a int numberOfGuesses in the main method before the if statement, and call playGame with numberOfGuesses = playGame(...), then System.out.println("You guessed " + numberOfGuesses + " times."); after the if-statements.
I think this is what you're trying to do.
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r"
+ "1. 1-10 \r"
+ "2. 1-100 \r"
+ "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n==1) {
System.out.println("Guess count: "+playGame(10));
}
else if (n==2) {
System.out.println("Guess count: "+playGame(100));
}
else if (n==3) {
System.out.println("Guess count: "+playGame(1000));
}
else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int)(Math.random() * maxNumber) +1;
int guessCount = 0;
boolean bool = false;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (! bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
bool = giveResponse(answer, guess);
}
return guessCount;
}
public static boolean giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
return true;
}
else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
return false;
}
else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
return false;
}
}
}
Here is your complete solution
import java.io.Reader;
import java.util.Scanner;
public class HereSOl {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r" + "1. 1-10 \r" + "2. 1-100 \r" + "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n == 1) {
System.out.println("Guesstcount : " + playGame(10));
} else if (n == 2) {
System.out.println("Guesstcount : " + playGame(100));
} else if (n == 3) {
System.out.println("Guesstcount : " + playGame(1000));
} else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int) (Math.random() * maxNumber) + 1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
boolean ans =giveResponse(answer, guess);
if (ans == true) {
break;
}
}
return guessCount;
}
public static boolean giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
return true;
} else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
return false;
} else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
return false;
}
return false;
}
}
I think you should use enum, Here is my Solution.
import java.util.Scanner;
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r" + "1. 1-10 \r" + "2. 1-100 \r" + "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n == 1) {
playGame(10);
} else if (n == 2) {
playGame(100);
} else if (n == 3) {
playGame(1000);
} else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int) (Math.random() * maxNumber) + 1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
Answer ans = giveResponse(answer, guess);
System.out.println(ans.getMessage());
if (ans == Answer.CORRECT) {
bool = false;
System.out.println("You took " + guessCount + " guess to get right number.");
}
}
return guessCount;
}
public static Answer giveResponse(int answer, int guess) {
if (guess == answer) {
return Answer.CORRECT;
} else if (guess > answer) {
return Answer.HIGH;
} else {
return Answer.LOW;
}
}
private enum Answer {
CORRECT("Your guess is correct!\r"), HIGH("Your guess is too high, guess again:\r"), LOW("Your guess is too low, guess again:\r");
private String message;
public String getMessage() {
return this.message;
}
Answer(String message) {
this.message = message;
}
}
}
Related
i am having trouble passing the value of "guess" into my main method. The
method that is trying to return guess just shows up as zero in the main.I have tried various things such as void methods and different returns but the guess value does not get updated in the while loop of the main even though, from what i am seeing, it should be getting updated from the method and passing it down to the guesses right below it.
import java.util.*;
public class assignment052 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int userGuess = 0;
int compNum = 0;
int guess = 0;
int totalGuesses = 0; //
int best = 9999; //
introduction();
int games = 0;
String playAgain = "y";
while(playAgain.equalsIgnoreCase("y")) {
System.out.println();
System.out.println("I'm thinking of a number between 1 and 100...");
games++;
guessNumber(console, userGuess, compNum, guess);
System.out.println(guess);
totalGuesses += guess;
System.out.println("Do you want to play again?");
Scanner newGame = new Scanner(System.in);
playAgain = newGame.next();
if (best > guess) { //
best = guess; //
}
}
result(games, totalGuesses, best);
}
// Method that introduces the game
public static void introduction() {
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("100 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.");
}
// method to play 1 game
public static double guessNumber(Scanner console, int userGuess, int compNum, int guess) {
Random rand = new Random();
userGuess = console.nextInt();
guess = 1;
compNum = rand.nextInt(100)+1;
while(compNum != userGuess) {
if(compNum > userGuess) {
System.out.println("It's higher.");
} else {
System.out.println("It's lower.");
}
guess++;
userGuess = console.nextInt();
}
System.out.println("you got it right in " + guess + " guesses");
return guess;
}
// method for overall result
public static void result(int games, int totalGuesses, int best) {
System.out.println("Overall results:");
System.out.println();
System.out.println("Total games played : " + games);
System.out.println("Total guesses : " + totalGuesses);
System.out.println("Guesses per game : " + totalGuesses / games);
}
}
I am a new human learning to code!
I had a problem with my Scanner, which is that I need it to 'reset' on an invalid character.
My code:
public class Lemonade {
static int m = 150;
private static Scanner scan;
public static void main(String[] args) {
int day = 1;
for(int gameover = m; gameover > 0; day++) {
int Random = (int) (Math.random() * 100);
if(Random <= 25) {
System.out.println("Great Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 50) {
System.out.println("Good Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 75) {
System.out.println("Bad Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 100) {
System.out.println("Awful Chance!");
System.out.println("--------------------------------");
}
int count = 0;
int none = 0;
scan = new Scanner(System.in);
System.out.println("Enter a number between 0 and " + m + "!");
count = scan.nextInt();
if(count >= none && count <= m) {
System.out.println("You entered " + count + "!");
System.out.println("--------------------------------");
day = day + 1;
m = m - count;
System.out.println("Day " + day);
}
else {
System.out.println("Enter a number between 0 and " + m + ".");
count = scan.nextInt();
}
}
}
}
Now is my question how to get this to 'reset' on an invalid character like 'f', as Scanner only accepts numbers.
Thanks for the help!
If I understand you correctly then this is something you're looking for,
InputMismatchException will thrown if user enters invaild characters instead of int. You may use looping until the user enters an integer
import java.util.Scanner;
import java.util.InputMismatchException;
class Example
{
public static void main(String args[])
{
boolean isProcessed = false;
Scanner input = new Scanner(System.in);
int value = 0;
while(!isProcessed)
{
try
{
value = input.nextInt();
//example we will now check for the range 0 - 150
if(value < 0 || value > 150) {
System.out.println("The value entered is either greater than 150 or may be lesser than 0");
}
else isProcessed = true; // If everything is ok, Then stop the loop
}
catch(InputMismatchException e)
{
System.out.print(e);
input.next();
}
}
}
}
If this is not you're looking for please let me know!
I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.
I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.