So I am having an issue figuring out how to create a loop and bring another class over in a dice game application I have to create for a school project. The game has to keep user score for each round 18 is the max score and if a user Rolls over 10 in 1 round his points are lost and he starts the next round at 1 point. The game also has to validate when the user enters Y to Roll or R to stop. Some help on this would be greatly appreciated. Im having problems with setting up a loop in which to continue the game after Y is entered or Tell the user the game has stopped after R is entered. So after Y is entered the loop would Print out "Round1" Roll:6 [Y or R], user entered Y, Print out "Round 2" and so on and i dont know how to validate user input.
import java.util.Scanner;
import java.util.Random;
import java.lang.Boolean;
public class Player {
public static void main(String[] args){
String player;
String playerAnswer;
Boolean answer = true;
int RoundScore;
int TotalScore;
int playerScore;
int Round;
Scanner user = new Scanner(System.in);
System.out.println("Enter your First Name to play!");
player = user.nextLine();
playerAnswer = user.nextLine();
{
System.out.println("Your Name:" + "" + player);
System.out.println("Welcome" + "" + player + "" + "To Dice Game");
System.out.println("Enter Y to Roll or R to STop:[Y or R]" + "" + playerAnswer.toUpperCase());
}
}
}
package Project4;
import java.util.Random;
import java.util.Scanner;
public class Dice{
public static void main(String[] args){
Random dice = new Random();
int number = 0;
for(int counter = 1; counter <= 1; counter++)
number = 1 + dice.nextInt(18);
System.out.println(number + "");
}
}
Something for you to note I don't think there's a (1) die can roll up to 18. The range for 3 dice should be 3 - 18 instead of 1 - 18.
number = 3 + dice.nextInt(16);
For the loop issue use do while loop, and assign a variable to get the and noticed how your playerAnswer should be under the System.out.println.
int rounds = 1;
do {
// codes that you want to loop
System.out.println("Welcome" + "" + player + "" + "To Dice Game");
System.out.println("Round " + rounds); // this will annouce the number of rounds
System.out.println("Enter Y to Roll or R to STop:[Y or R]")
playerAnswer = user.nextLine();
rounds++;
} while (playerAnswer.equalsIgnoreCase("y");
Also, I don't think you can have 2 main method here as you're creating "an" application, not 2 different application. I would suggest that you create a sub method using
public static void rollDice()
{
// codes for rolling the dice
}
and to call the rollDice method just do a
rollDice();
However, the application you're creating seems to be small and doing just the dice roll, if I am you I wouldn't even need to create a method for it.
You are probably trying to learn how to create a class. Seeing your codes, you seems like you aren't that great in Java yet. I would suggest that you re-start learning Java from the basics. I think you need to pay more attention in your school class.
Related
Hello my task is to write a program that selects a random number between 1 and 5 and asks the user to guess the number. Then I must display a message that indicates the difference between the random number and the users guess. I then must display another message that displays the random number and the Boolean value true or false depending on whether the user's guess equals the random number. I have got the first part of the assignment done, where the user guesses a number and the computer generates a random number between 1 and 5, but I don't have a clue on how to make it display how close or far off they were or how to use a Boolean to show if the guess was equal to the number or not. I have left code of what I have so far. Thanks for the help and sorry if there is anything wrong with this post.
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
I need the first message to read something like "You were 3 numbers off." and the second message needs to read something like "You guessed the number 3 correctly" or "You did not guess the number 3 correctly."
Take the absolute value of the entered number subtracted by the random number.
Something like:
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
Based on Zachary McGee's answer:
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
String input = JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
if(Integer.parseInt(input) == random)
JOptionPane.showMessageDialog(null, "You guessed correctly!");
else
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - Integer.parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
If you have any questions to the code, feel free to ask :)
Hey guys I'm working some exercises from the Think java textbook. I'm working on exercise 3-4 on chapter 4 and I finished writing the code and it works when I run it the first few times but when I try running it again it prints the number generated not the number guessed.
import java.util.Random;
import java.util.Scanner;
public class GuessMyNumber {
//exercise 3-4
public static void main (String[]args) {
//pick a number
int numberGuessed;
int numberGenerated;
int difference;
//generate a random number
Random random = new Random();
numberGenerated = random.nextInt(100) + 1;
Scanner sc = new Scanner(System.in);
//prompt for user input
System.out.println("Im Thinking of a Number between 1 and 100 \nCan you Guess what it is? ");
System.out.print("Type a Number: ");
numberGuessed = sc.nextInt();
System.out.println("Your Guess is: " + numberGuessed);
System.out.println("The Number I was Thinking of is: " + numberGenerated);
//modulation operator
difference = numberGenerated % numberGuessed;
System.out.println(difference);
System.out.printf("you were of by: %d", difference);
}
}
I think what you are confused about is the modulo operation. At least the text does not fit to what it is doing. To calculate what was the difference between the two numbers you would just do
difference = numberGenerated - numberGuessed;
When you don't want to have negative values you could use
difference = java.lang.Math.abs(numberGenerated - numberGuessed);
The modulo operator gives you the rest of a division.
I'm generally new to programming and just started programming in Java a few days ago so I'm not sure if what I'm trying to accomplish is even possible with the way my program is coded.
I'm basically writing a program that asks for a "Strength" value between 0 and 9. It asks you to choose a weapon ((1) Knife is the only one available). It takes that information and generates a random damage ratio between 1-3 plus what ever number your strength is and is supposed to keep subtracting that value from 20 until it hit 0 then quits.
The problem is that I'm stuck in a loop. It subtracts the value from 20, but starts over and keeps subtracting from 20 again rather than storing the subtracted number.
Does anyone have any advice on how something like this would be accomplished? Any help is very much appreciated. This is my code so far....
package untitledgame;
import java.util.Random;
import java.util.Scanner;
public class UntitledGame {
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is "+pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
Scanner scanner = new Scanner(System.in); //waits for users to continue
scanner.nextLine();
if (wKnife == 1){
do {
int enemyHP = 20;
Random rn = new Random(); //Random generator
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " ); //Knife damage
System.out.print(+damage);
System.out.print(" damage." );
System.out.println("");
enemyDamage = enemyHP - damage; // Remaing HP
System.out.println("Enemy has ");
System.out.print(+enemyDamage);
System.out.print(" HP left.");
System.out.println("");
System.out.println("Press Enter to Attack...");
scanner.nextLine();
}
while (enemyDamage > 0);
System.out.println("Enemy has been defeated.");
}
}
}
Declare this int enemyHP = 20; outside the do-while loop. Right now, you're resetting enemyHP to 20 every single time you iterate through the loop.
Also, you should not recreate your Random within the do-while loop. Do that before entering the do block.
There are other issues with the logic that Jonah Haney deals with in his answer.
You'll want to initialize your enemyHP variable OUTSIDE of the do-while loop, or it will reset enemyHP back to 20 every time it loops.
Declare int enemyHP = 20 before the beginning of the loop. Then your loop is missing the following line:
enemyHP = enemyHP - damage;
Also, it seems that you want the loop to keep running until the enemy has been defeated. If that is the case, then your condition should check to see if enemyHP has been drained all the way, like this:
}
while (enemyHP > 0); //instead of while (enemyDamage > 0);
EDIT
This is what your code SHOULD look like. I am not saying you should copy it straight into your project. I am saying that you should take a look at the differences and it will help you see the logic problems in your own code:
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is " + pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
in.nextLine();
in.nextLine();
Random rn = new Random(); //Random generator
int enemyHP = 20;
if (wKnife == 1){
do {
System.out.println("Press Enter to Attack...");
in.nextLine();
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " + damage + " damage."); //Knife damage
enemyHP -= damage; // Calculate Remaining HP
System.out.println("Enemy has " + enemyHP + " HP left.");
} while (enemyHP > 0);
System.out.println("Enemy has been defeated.");
in.close();
}
}
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.
I am building a game for Java and I've gotten down to one of the last parts. There are still other things to fix which are easy fixes. Although there is one problem I can't figure out, which is that after every time I run the game I can't get new random numbers to show up.
For instance, if nobody guesses the number that is made at random by the computer from numbers (1-20) than the game repeats itself. You are playing 2 computers during this and their numbers are also made up at random (again 1-20 values).
Here is some of the code for the Player class I made
import java.util.Scanner;
import java.util.Random;
public class Player {
private double currentGuess = 0;
private String firstName;
private boolean isCorrect;
Scanner myScanner = new Scanner(System.in);
public Player() {
}
public double autoGuess() {
Random randomNumber = new Random();
double number = randomNumber.nextInt(20) + 1;
return number;
}
Here is my GuessGame class, which is where the action actually happens. I cannot figure out why when I call for the autoGuess method (from the player class) I cannot get new random numbers to show up after each game which resulted in nobody guessing the right number. Same goes for randomly generating the number to be guessed (WINNING_NUMBER), it still stays the same after every new game. Here is some of the code of my GuessGame class.
import java.util.Random;
public class GuessGame {
Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
double player2Guess = player2.autoGuess();
double player3Guess = player3.autoGuess();
int numberOfTries = 0;
public double generateWinningNumber() {
Random randomGenerate = new Random();
double randomNumber = randomGenerate.nextInt(20) + 1;
return randomNumber;
}
private final double WINNING_NUMBER = generateWinningNumber();
public void startGame() {
System.out.println("VM: Welcome we are going to play a number guessing game. I'm (the JVM)\n"
+ "going to randomly pick a number between 0 and 20. You and the 2 other\n"
+ "computer-generated players are going to try to guess that number. The game\n"
+ "will end when at least one of the players correctly guesses the number.\n");
System.out.println(WINNING_NUMBER);
System.out.print("What is your name? ");
String player1Name = player1.readName();
while (player1.isCorrect() == false)
{
System.out.print(player1Name + ", enter your guess: ");
player1.readGuess();
player2.autoGuess();
player3.autoGuess();
numberOfTries++;
if (player1.getCurrentGuess() == WINNING_NUMBER || player2Guess == WINNING_NUMBER || player3Guess == WINNING_NUMBER)
{
player1.setCorrect(true);
displayGuesses();
determineWinner();
}
else
{
displayGuesses();
displayHints();
System.out.println("No one guessed the number.\nPlayers will need to guess again.\n");
System.out.println("The winning number was: " + WINNING_NUMBER);
generateWinningNumber();
}
}
}
public void displayGuesses() {
System.out.print("Player 2's guess is: " + player2Guess + "\n");
System.out.print("Player 3's guess is: " + player3Guess + "\n\n");
}
There is more to this and obviously more to fix, but I'm trying to just get this issue out of the way. I have my driver class starting this game and also know I need to round my numbers to Ints so there isn't a decimal place. Also, all the hint method is referring to is just if statements that tell you if you are hot, warm, or cold. That runs perfectly fine. Just needing some help with figuring out how to get a new random number after every new unsuccessful game from my while statement.
Your generateWinningNumber() method returns a double, it does not actually change any values itself. Also, because WINNING_NUMBER is a constant, even if you did want to change it, you wouldn't be able to. You should definitely not make WINNING_NUMBER final, and either modify generateWinningNumber() so that it modifies your global variable itself, or leave it as-is and use its return value to assign to your non-constant winningNumber global.