Two console inputs required to System.exit(0) during else if - java

So I'm working on a copy of a simple Dice game that was an example from the Maxwell Sanchez YouTube JAVA on Eclipse tutorials. What I started playing around with is simple ways to implement a text based menu of sorts.
What I'm trying to accomplish is a Y or N input method of either restarting the program, or killing it. I'm a total noob, coming here after a tiny bit of Arduino. I'm liking JAVA but there are many things I don't understand.
My problem right now is, everything appears to work so far, except that if you get to the end and type N to quit, It requires 2 inputs of N to actually execute the else if statement. Is that something that is a bug? Or am I just mis-programing what I'm trying to accomplish.
import java.util.*;
public class diceGame
{
static int money;
static Scanner in = new Scanner(System.in);
static Random random = new Random();
static String userName;
static String tryAgain;
public static void main(String[] args)
{
money = 1000;
System.out.println("Welcome to this simple dice game! " +
"Please enter your name.");
String userName = in.nextLine();
System.out.println("Hey " + userName + ".");
rollDice();
}
public static void rollDice()
{
System.out.println("You have " + money + " coins!");
System.out.println("Please select a number (1-6) to bet on!");
int betRoll = in.nextInt();
System.out.println("Please place your bet!");
int betMoney = in.nextInt();
while (betMoney > money)
{
System.out.println("You don't have enough coins... you only " +
"have " + money + "coins.");
System.out.println("Please place a realistic bet!");
betMoney = in.nextInt();
}
int dice;
dice = random.nextInt(6)+1;
if (betRoll == dice)
{
System.out.println("You Win!");
money+=betMoney*6;
System.out.println("You have " + money + " coins.");
}
else
{
System.out.println("Snap! You lost your coins!");
money-=betMoney;
System.out.println("You have " + money + " coins.");
}
if (money <= 0)
{
System.out.println("You've lost all yer coins!");
System.out.println("Play again?" + " Type y or n");
if (in.next().equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (in.next().equalsIgnoreCase("n"))
{
System.out.println("Maybe next time...");
System.exit(0);
}
else
{
System.out.println("Invalid character");
}
}
else
{
rollDice();
}
}
}

Store the input in a variable, and compare it... or you'll have to input twice.
String choice = in.next();
if (choice.equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (choice.equalsIgnoreCase("n")) // <-- not in.next()
Every time you call in.next() you read user input.

if (in.next().equalsIgnoreCase("y"))
else if (in.next().equalsIgnoreCase("n"))
In this code, you are calling in.next() twice, once for each condition, so it will read two inputs.
You need to separate the reading from the comparison.
String input = in.next();
if (input.equalsIgnoreCase("y"))
else if (input.equalsIgnoreCase("n"))

Related

How to make 'end game' method in java

so i made a game, in which user needs to guess the random number or letter. I want to make it so that when the user writes 'end game' during the game (when he guesses the number), he is being redirected to the menu (using the main(args); method). In fact, String value cannot be writen in int input. So when i write 'end game' during the game cycle, it just crashes. What should i do?
Heres code of my game:
import java.util.Scanner;
public class TwoGames {
public static void main(String[] args) { // main menu
Scanner scan = new Scanner(System.in);
System.out.println("Choose the game\n Type 'letter' or 'number' to choose the game");
String UserAnswer = "";
UserAnswer = scan.next();
if (UserAnswer.equalsIgnoreCase("number")) {
number(args);
}else if(UserAnswer.equalsIgnoreCase("letter")){
letter(args);
}
scan.close();
}
public static void letter (String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
public static void number(String[] args) { //heres the number guessing game
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";//variable to stop game
do {
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
do {
int guess = 0;
while (guess != theNumber) {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
} while (Stop.equalsIgnoreCase("end game"));
main(args);// this sends user to main menu
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
}
I am novice programmer, so yeah, thats might be a dumb question, because im learning. Anyway, any help and explanation would be useful.
To solve this problem, you should input a string, check if it equals to "End game" message and if not continue your code.
For example, replace this line:
guess = scan.nextInt();
In this code:
String input = scan.next();
if(input.equals("End game")){
main(args);
return;
}
guess = Integer.parseInt(input);
That code get a String input called input, check if he equals to "End game" and if not continue your guess loop.

How do I start a different method over after another Method has finished in java?

I'm making a gambling game. The player enters a bet amount. After that a die is rolled three times, then based on the value of the die rolls, 1 of 4 things happen. Then you get to start again with the new Pot amount. I cant figure out how to start it again. I tried putting the method name i want to start at the end of the last method in the sequence and it kinda of works. It starts but when i put in a bet amount it doesnt do anything.
Here is my code
import java.util.Scanner;
public class Game {
private double Bet;
private double Pot = 50;
// private double TotalPot;
private int[] die = new int[3];
public Game() {
Pot = 50;
Bet = 0;
}
public void introText() {
System.out.println(
"Welcome to game Bet an amount.\nIf all of the three die together is greater than 12, \nyou get to keep your bet, if you roll doubles you win \ndouble your bet, if you roll triples you win triple \nyour bet. If your roll meets non of this criteria you lose your bet.A bet of 0 \nends the game.");
}
public void inputBet() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your bet: ");
Bet = keyboard.nextDouble();
if (Bet > Pot) {
System.out.println(
"Error, Bet out of range. Please enter a bet amount that is lower or the same as the current Pot. ");
inputBet();
} else if (Bet == 0) {
System.out.println("Thank you for playing. You end the game with a pot of " + Pot);
System.exit(1);
} else if (Bet < 0) {
System.out.println("Error,");
inputBet();
}
}
public void removeBet() {
Pot = Pot - Bet;
}
public void rollDie() {
Die bob = new Die();
int total = 0;
for (int i = 0; i < 3; i++) {
die[i] = bob.rollDie();
System.out.println("Your die number is listed below");
bob.displayDie(die[i]);
total = total + die[i];
}
bob.displayDie(total);
}
public void displayingDie() {
System.out.println("Pot amount before dice rolls $" + Pot);
}
public void dieComparison1() {
if ((die[1] == die[2]) && (die[0] == die[2])) {
Pot = (Bet * 3) + Pot;
System.out.println(+Pot + "if theyre all equal");
} else if ((die[0] == die[1]) || (die[0] == die[2]) || (die[1] == die[2])) {
Pot = (Bet * 2) + Pot;
System.out.println(" Congradulations! You win double your bet.");
} else if (die[0] + die[1] + die[2] > 12) {
Pot = Pot + Bet;
System.out.println("You win. But only your bet amount back");
} else if (die[0] + die[1] + die[2] < 12) {
// Pot = Pot - Bet;
System.out.println("Sorry You lose you bet amount");
}
}
public void print() {
System.out.println("The current Pot amount is: " + Pot);
inputBet();
}
}
You have a conception problem. You should not control your execution flow nor do io actions from your Game class. This is mainly a problem of separation of concerns. Each method of this class should only do actions relative to gambling. For exemple inputBet must only change bet and do controls, in fact it must only be a setter and be renamed setBet and throws IllegalArgumentException for exemple.
You can then do something like this in your main :
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Game game = new Game();
while(true){
Double bet = keyboard.nextDouble();
if(bet == 0){
//main loop break case
break;
}
try{
game.setBet(bet);
}catch(IllegalArguementException excpt){
system.out.println("error " + excpt.getMessage());
// skip next steps and do new loop iteration
continue;
}
// rest of execution flow
game.rollDice();
game.displayDice();
game.compareDice();
game.print();
}
System.exit(0);
}
and the setBet method could be :
public void setBet(Double bet){
// Range controls
if (bet > Pot || bet < 0) {
Throw new IllegalArgumentException("Bet out of range. Please enter a bet amount that is lower or the same as the current Pot. ");
}
this.bet = bet;
}

How to replay basic High Low game?

I am almost finished with my second Java assignment for class, but I am stuck on how to take the user's last choice and either play again or quit. Any ideas?
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
String userGuess = null;
boolean gameWin = false;
do {
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine();
}
}
}
The problem is because you have userInput.nextLine() prompt for the user to play again or not outside of the game loop and it isn't assigned to any value. I am referring to this section...
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine(); <---
}
To fix this problem you simply need to assign the final input call to userGuess and place it back into the game loop like so.
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
Doing this will assign the play again value you prompt the user for into the variable that your testing with the do-whileloop. In your original, you had the condition testing for a value that userGuess wasn't going to be storing and instead prompting the user for that option AFTER the loop would have been exited instead of inside where it needs to be.
To reset the values for the next game, you can simply move the variables' initialization into the game loop at the top like so...
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int numberOfTries, answer;
Scanner userInput = new Scanner(System.in);
String userGuess;
boolean gameWin;
do {
answer = randomNumber.nextInt(100) + 1;
gameWin = false;
userGuess = null;
numberOfTries = 0;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
}
}
this way every time the game loops through, all the values will be reset at the beginning of the new game loop.
Also you should close the Random object and Scanner object at the end of the entire program using close() on each instance.
You need to initialize most of your variables and call userInput.nextLine(); inside your outer loop. Untested suggestion:
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
String userGuess = null;
do {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
boolean gameWin = false;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
userInput.nextLine();
while (userGuess.equals("yes"));
}
}
}

How to ask user to Play Again....Guess Game

I'm making a simple guess game but I don't know how to ask the player if the want to play the game again.Everytime the game ends I have to run the game again so I want to add this feature to it.I looked in some other posts but they didn't help.Here's the code:
import java.util.*;
public class guessNumber{
private static Scanner userInput = new Scanner(System.in);
public guessNumber(){
System.out.println("~~~Guess Game~~~");
}
public void guessGame(){
System.out.println("Enter the maximum number:");
int maxNum = userInput.nextInt();
System.out.println("Guess a number between 0 and " + maxNum + ":");
int randomNumber = (int) (Math.random() * maxNum);
boolean gameOn = true;
int numberOfTries = 0;
while(gameOn){
boolean printOthers = true;
numberOfTries++;
int number = userInput.nextInt();
if(number > maxNum){
System.out.println("Please enter a number between 0 and " + maxNum + ".");
printOthers = false;
}
if(printOthers){
if(number == randomNumber){
System.out.println("=================================");
System.out.println("You guessed the right number xD.");
System.out.println("Your tried " + numberOfTries + " times.");
System.out.println("=================================");
}else if(number > randomNumber){
System.out.println("Try a lower number");
}else if(number < randomNumber){
System.out.println("Try a higher number");
}
else{
System.out.println("Please enter a number between 0 and " + maxNum + ".");
}
}
}
}
public static void main(String[] args){
guessNumber guess = new guessNumber();
guess.guessGame();
}
}
In your main use a while loop. In the loop first call your guessGame() then, similarly to how you ask to enter a number, you ask if they want to play again (Y/N ?) and if they say no you break the loop otherwise you go ahead...
Add your calling method in main method with in a while loop
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
do{
//call your game
System.out.println("Do you want to play again. Press y");
}
while(scanner.next().equals("y"));

The Pig Dice Game Human vs Computer Java Program

I have been working on this program for about a week now and I think I have it down pack. The issue I am having when I ask the user at the beginning of the game (human vs computer) every time I run the program it asks me what my name is again. Here is what I have thus far:
import java.util.Scanner;
public class Assignment
{
Scanner usersName;
Boolean humanTurn = true;
Boolean computerTurn = true;
int dice;
int humanTurnPoints, computerTurnPoints;
int humanTotalPoints = 0;
int computerTotalPoints = 0;
private Scanner keyboard;
private Scanner key;
//System.out.print("Please enter your name: ");
//usersName = new Scanner(System.in);
//setStart(usersName.nextLine());
public void roll()
{
dice = (int)(Math.random()*6) + 1;
}
public int humanTurnScore()
{
{
humanTurnPoints = dice + humanTurnPoints;
System.out.println("You threw: " + dice);
System.out.println("You have scored: " + humanTurnPoints + " in your turn.");
} return humanTurnPoints;
}
public void humanTurnZero()
{
humanTurnPoints = 0;
}
public int computerTurnScore()
{
{
computerTurnPoints = dice + computerTurnPoints;
System.out.println("Computer has scored: " + computerTurnPoints + " in its turn.");
} return computerTurnPoints;
}
public void computerTurnZero()
{
computerTurnPoints = 0;
}
public Assignment()
{
humanGame();
if(!humanTurn)
{
computerTurn();
}
}
public int humanGame()
{
System.out.println("To start the game please press 'r'.");
key = new Scanner(System.in);
String start = key.nextLine();
if(!start.equalsIgnoreCase("R"))
{
System.out.println("Make sure you are pressing 'r'.");
humanGame();
}
if(start.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets start.");
do{
roll();
if(dice == 1)
{
System.out.println("You got 1 and you lost your turn.");
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
humanTurnZero();
computerTurn();
}
else if(dice != 1)
{
humanTotalPoints += dice;
if(humanTotalPoints >= 100)
{
System.out.println("You threw: " + dice);
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Congratulations, you win!");
System.exit(0);
}
humanTurnScore();
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("You can hold or roll again.");
System.out.println("To roll again press 'r' or 'h' to hold.");
keyboard = new Scanner(System.in);
String choice = keyboard.nextLine();
if(choice.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets roll again.");
roll();
if(!choice.equalsIgnoreCase("R"))
{
System.out.println("You didn't press 'r'. To make sure the program is running correctly please press 'r' to roll or 'h' to hold.");
humanGame();
}
}
if(choice.equalsIgnoreCase("h"))
{
System.out.println("You pressed 'h' and loose your turn.");
System.out.println("Your Grand total is: " + humanTotalPoints);
humanTurnZero();
computerTurn();
}
}
}while(humanTurn);
}return dice;
}
public int computerTurn()
{
System.out.println("Now it's computer turn.");
do {
roll();
if(dice != 1)
{
computerTotalPoints += dice;
if(computerTotalPoints >=100)
{
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Game Over! the computer wins");
System.exit(0);
}
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Your Grand total is: " + humanTotalPoints);
computerTurnScore();
roll();
}
if(dice == 1)
{
System.out.println("Computer thrown 1 therefore it's your turn now.");
computerTurnZero();
humanGame();
}
if(computerTurnPoints >= 20)
{
System.out.println("Computer scored already " + computerTurnPoints + " you'd better start to focus.");
System.out.println("Please play again");
humanGame();
}
}while (computerTurn);
return dice;
}
public static void main(String[] args)
{
new Assignment();
}
}
I commented out (up close to the top of the program) where I am asking the user at the beginning of the program what their name is. I actually need in all the System.out.println where it says 'You' I need it to say the usersName.
Would someone please help me with this program. I know someone is kind enough to help me out here.
Thank you in advance.
Of course it will ask you that every time!
You need to save this in a file, and then read from it!
//Write
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println(usersName.nextLine());
writer.close();
//Read
BufferedReader br = new BufferedReader(new FileReader("the-file-name.txt"));
try {
while (line != null) {
usersName = line;
line = br.readLine();
}
} finally {
br.close();
}
Add your logic for determining if there is sth in that file yourself please.
Okay, I think you might be getting confused about the lifetimes of variables. In java, variables like String username; exist only in their own scope.
If you define a variable inside a method, it will be forgotten about when the program exists the method.
If you define it as a field inside a class (what you were doing), it will only exist as long as the instance of the class exists. As soon as the program forgets about the instance of the class, it also forgets about anything attached to that instance, including its variables.
Once the program shuts down, the computer naturally forgets about all objects that the program held, and so the username ceases to exist.
If you want the program to remember some value across shutdowns, you have to store that value in a file or a database or whatever. I recommend using a file, to make a database for this would be overkill squared. I will refer you to Roberto's answer from an hour ago for more info on how to achieve this exacly.

Categories