So I'm writing some code for a card game and within this card game I have coded how the first round works. My question is how I would be able to repeat this code over and over again until the cards run out( since each card can only be used once). I'm thinking that I have to use a while loop. For convenience I will explain what each of the methods here do so that you may understand, so please bear with me. Some of this is useless code that I haven't gotten to complete yet and make useful.3
The rules to the game : https://tobakumokushirokukaiji.fandom.com/wiki/E_Card
** Here are the methods : **
typeOfCard(); - this tells you which side you are playing on and is decided randomly, so far you can only play on the Emperor side.
winOrLose() - this is the last method i worked on before making this post, this is what I am trying to implement to allow me to replace the current win or loss output as strings which i can call easier than print statements. I want to make this so that the games which are won can set the int wincounter to 1 so it can print this out.
emperorsTurn() - this is the method that asks the main questions of which card you would like to play versus the computer.
wincounter() - some code i need to delete so dont worry about this
import java.util.Random;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args) {
int numberOfCards = 7;
if (numberOfCards > 6) {
numberOfCards--;
//System.out.println("your number of cards is " +numberOfCards);
}
typeOfCard();
}
public static void typeOfCard() {
Random card = new Random();
int number = 0;
for (int counter =1; counter <=3;counter++){
number = 1+card.nextInt(2); }
if (number == 1) {
System.out.println("your are playing on the emperor side");
}
if (number ==2){
System.out.println("You are playing on the slave side ");
}
if (number ==1){
emperorsTurn();
}
}
public static void winOrLose(){
int wincounter = 0;
String win = "You won the round";
String lose = "You lose the round ";
if (wincounter >0) {
System.out.println(win);
}
else if (wincounter == 0) {
System.out.print(lose);
}
}
public static void emperorsTurn() {
Random cards = new Random();
int computerinput = 0;
for (int counter = 1; counter <= 3; counter++) {
computerinput = 1 + cards.nextInt(2);
}
Scanner sc = new Scanner(System.in);
System.out.println("Please pick the card you are playing. \n if you are playing the Emperor press 1, if you are playing the citizen press 2 ");
int userinput = sc.nextInt();
if (userinput == 1 && computerinput == 1) {
System.out.println("you have played the emperor! \n the emperor is defeated by the slave");
}
else if (userinput ==1 && computerinput ==2) {
System.out.println("you have played the emperor the emperor defeats the citizen");
winOrLose();
wincounter();
}
else if (userinput == 2) { //when the user input is 2
if (computerinput == 1) {
System.out.println("you have played the citizen, this defeats the slave");
wincounter();
} else if (computerinput == 2) {
System.out.println("you have played the citizen, this ties with the citizen");
}
//print out something else if number is not 1,2 or 3
}
}
public static void wincounter() {
int i = 0;
if (i < 1)i++;
System.out.println("you have won " +i +" number of draws");
}
}
Try doing a while loop that compares the number of cards left to the minimum number needed to play a game.
while (numberOfCards > minNumberNeeded) {
playGame();
}
Related
The goal of the game is to use a while loop. In this loop, it will determine who wins the game based on the number entered. The numbers are from 1 to 20. Challenge is the variable set at 10. If <= Challenge, playerOne loses one point. If > challenge, the monster loses a point. Whoever loses 3 points first loses the game. I do not need to have random number generation, I just need inputs via the scanner function.
I thought variables were necessary for the scanner, which is why I added the Dice variables. They are not used and I am confused if I need them or not to make the scanner work so that the user can make inputs.
I am also confused on how to subtrack from the player and monster when they get hit. Which is why I set the variables under each block for the amount of points they have. This is wrong but I am stuck as to how to properly display this.
I was able to get some messages to display, but any number would give me the same result which was -1 for player one.
Essentially I am stuck on how to write this in code from here. Any help is greatly appreciated.
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
task3(20);
}
public static void task3(int challenge) {
challenge = 10;
int player = 3;
int monster = 3;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your dice roll");
int diceRollOne = sc.nextInt();
while (player <= challenge) {
System.out.println("Monster misses");
System.out.println("Enter your dice roll");
int diceRollTwo = sc.nextInt();
continue;
if (player <= challenge) {
System.out.println("-1 for player");
player = 2;
System.out.println("Enter your dice roll");
int diceRollThree = sc.nextInt();
} else if (player > challenge) {
System.out.println("-1 for monster");
monster = 2;
System.out.println("Enter your dice roll");
int diceRollFour = sc.nextInt();
continue;
if (player <= challenge) {
System.out.println("-1 for player");
player = 1;
System.out.println("Enter your dice roll");
int diceRollFive = sc.nextInt();
continue;
if (player > challenge) {
System.out.println("-1 for monster");
monster = 1;
System.out.println("Enter your dice roll");
int diceRollSix = sc.nextInt();
continue;
} else if (player <= challenge) {
System.out.println("-1 for player");
player = 0;
System.out.println("Monster Wins");
int diceRollSeven = sc.nextInt();
continue;
if (player > challenge) {
System.out.println("-1 for monster");
monster = 0;
System.out.println("Player wins!");
int diceRollEight = sc.nextInt();
}
}
}
}
}
}
}
When you are writing a while-loop, you must first think about the condition of when will the loop terminate / when will the loop continue. In your case, you want the loop to end when either player or monster become 0. Therefore the condition for the while-loop to continue running is the opposite, i.e. both of them > 0.
Then think about what do you want to do in each iteration. In your case, the repetitive tasks are
Read an integer from user input
compare the integer with challenge
subtract 1 point from the corresponding variable
Finally, after the loop ended, you can use the value of player and monster to determine the result and print it out.
import java.util.Scanner;
public class Task3 {
public static void main(String args[]) {
task3(10);
}
public static void task3(int challenge)
{
int player = 3;
int monster = 3;
int dice = 0;
Scanner sc = new Scanner(System.in);
while(player > 0 && monster > 0)
{
System.out.println("Enter your dice roll");
dice = sc.nextInt();
if(dice > challenge)
{
monster--;
}
else
{
player--;
}
}
if(player > monster)
{
System.out.println("Player wins!");
}
else
{
System.out.println("Monster wins!");
}
}
}
P.S. Try to understand the code instead of just copy and paste to your homework :)
You dont need to have a seperate variable to get each input from the scanner.
You can get the input each time in the while loop and compare the value to challenge.
we will exit the loop only when player or monster becomes zero.
once outside the loop, you can check who won and print the result accordingly.
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
task3(10);
}
public static void task3(int challenge) {
int player = 3;
int monster = 3;
Scanner sc = new Scanner(System.in);
int diceRoll;
while (player == 0 || monster == 0) {
System.out.println("Enter your dice roll");
diceRoll = sc.nextInt();
if(player < challenge)
player--;
else
monster--;
}
if(player < monster)
System.out.println("Player wins!");
else
System.out.println("Monster Wins");
}
}
if you want only numbers between 1 and 20 as the input, you should also add an if condition which checks this after getting the input
Write a program to simulate a coin toss. First, ask the user to "call" or predict the toss. Next, let the user know you are tossing the coin. Then report whether the user was correct.
Example:
Please call the coin toss (h or t): h
Tossing...
The coin came up heads. You win!
This is about what I am supposed to do. This is the code I have so far:
package inClassCh4Sec8to9;
import java.util.Random;
import java.util.Scanner;
public class ClassCh4Sec8to9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter you guess (1 for heads, 0 for tails, 2 to quit):");
int call = input.nextInt();
int heads = 1;
int quit = 2;
int tails = 0;
if (call == quit) {
break;
} else if (call == heads) {
} else if (call == tails) {
} else {
System.out.println("invalid");
continue;
}
Random random = new Random();
int coinflip = random.nextInt(2);
if(call == coinflip){
System.out.println("Correct!");
}else{
System.out.println("Sorry, incorrect.");
}
}
}
}
My problems:
I can get a random number no problem but it allows the h and t to be used as 1 and 0.
I want h or heads to equal 1 as an input.
Instead of Random.nextInt(), I would prefer nextBoolean(). Don't redeclare your Random in a loop. If the input starts with an h set a guess to true; otherwise, make sure it is valid (and set it false). Then flip the coin, and compare the result. Something like,
Scanner input = new Scanner(System.in);
Random random = new Random();
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine().toLowerCase();
boolean guess = call.startsWith("h"), coin = random.nextBoolean();
if (call.startsWith("q")) {
break;
} else if (!guess && !call.startsWith("t")) {
System.out.println("invalid");
continue;
}
if ((guess && coin) || (!guess && !coin)) {
System.out.printf("The coin came up %s. You win!%n", coin ? "heads" : "tails");
} else {
System.out.printf("The coin came up %s. You lose!%n", coin ? "heads" : "tails");
}
}
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine();
String heads = "h";
String tails = "t";
if(call==null || call.length() > 1){
break;
}
System.out.println("Tossing...");
int random=(int)(Math.random()*2);
if(random<1){ //assume that, if random variable is smaller than 1 then it is head. If bigger than 1 and smaller than 2, then tails.
if(heads.equals(call)){
System.out.println("The coin came up heads. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}else{
if(tails.equals(call)){
System.out.println("The coin came up tails. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}
}
}
}
My friend tried asking this question earlier and wasn't specific enough, so I'll try being a bit more detailed. We're trying to make a basketball simulator between two players that keeps playing until one player has reached 21 points, and then stops. We got fairly far, and while the program runs, it continues executing, instead of ending at 21 points for one player, and keeps running until I believe the program crashes. Does anyone have any idea on what needs to be added to prevent the program from executing after 21 points for one of the two players? I will post the code below, and if you would like a screenshot of the output, I would be happy to provide one. Thank you!
Code:
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.Random;
public class KobeVsLebron {
//VARIABLES
public Random randomGenerator;
private static int kscore = 0;
private static int lscore = 0;
//declare scanner
static Scanner input = new Scanner(System.in);
//main method
public static void main(String[] arguments) {
System.out.println("\n Welcome to Kobe vs Lebron Simulation");
System.out.println("In this simulation you will have a choice to flip a coin.");
System.out.println("Whatever the outcome of the flip is the starting players ball.");
System.out.println("The simulation is based off of a long standing argument");
System.out.println(" Kobe Bryant vs Lebron James in a game of 21.");
MainMenu();
}
/*******************************************************************************/
METHODS
//Main Menu
//PlayKobe
//PlayLebron
//LeaderBoard();
//ReadFile();
//WriteFile();
//Win();
private static void MainMenu(){
char choice;
do {
System.out.println("\nTo the run the simulation flip the coin by choosing 'F', \nTo print the leaderboard enter 'L' \nTo quit enter 'Q'");
choice = input.next().charAt(0);
switch (choice) {
case 'F':
case 'f':
FlipCoin();
break;
case 'L':
case 'l':
// LeaderBoard();
break;
case 'Q':
case 'q':
default:
System.out.println("Invalid Choice! TRY AGAIN!");
}
}
while (choice != 'Q');
}
private static void FlipCoin() {
Random randomGenerator;
int sides;
int currentsides;
System.out.printf("\nThe coin will be flipped heads(Kobe) or tails(Lebron)");
randomGenerator = new Random(); //initialize random object
sides = 2; //default number of sides
currentsides = randomGenerator.nextInt(sides)+1; //initialize roll (1-2)
System.out.printf("\nThe coin is being flipped.....");
//TIME DELAY '1000 is one second'
try {
Thread.sleep(1500);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
if(currentsides == 1 ){
System.out.printf("\nThe coin has been flipped to heads. \nKobe has the ball.");
PlayKobe();
}
if(currentsides == 2){
System.out.printf("\nThe coin has been flipped to tails. \nLebron has the ball.");
PlayLebron();
}
}
private static void PlayKobe() {
Random randomGenerator;
int shot;
//int kscore = 0;
int shotclock;
if(kscore < 22){
System.out.printf("\nKobe has won the game of 21!");
//Win();
}
randomGenerator = new Random(); //initialize random object
shot = 3; //default number of sides
shotclock = randomGenerator.nextInt(shot)+1; //initialize roll (1-2)
if(shotclock == 1){
System.out.printf("\nKobe drives in to the basket");
System.out.printf("\nLebron on his tail!");
System.out.printf("\nKobe scores the lay-up! and thats two for Kobe! ");
kscore += 2;
PlayLebron();
}
if(shotclock == 2){
System.out.printf("\nKobe dribbles towards the line ");
System.out.printf("\nLebron has him covered, Kobe takes the fade away shot!");
System.out.printf("\nScore! thats 3 points for Kobe!");
kscore += 3;
PlayLebron();
}
if(shotclock == 3){
System.out.printf("\nKobe is locked down and shaking!");
System.out.printf("\nLebron Steals the ball! ");
PlayLebron();
}
}
private static void PlayLebron(){
Random randomGenerator;
int shot;
// int lscore = 0;
int shotclock;
if(lscore < 22){
System.out.printf("\nLerbon has won the game of 21!");
//Win();
}
randomGenerator = new Random(); //initialize random object
shot = 3; //default number of sides
shotclock = randomGenerator.nextInt(shot)+1; //initialize roll (1-2)
if(shotclock == 1){
System.out.printf("\nLebron drives in to the basket");
System.out.printf("\nKobe on his tail!");
System.out.printf("\nLebron scores the lay-up! and thats two for Lebron!");
lscore += 2;
PlayKobe();
}
if(shotclock == 2){
System.out.printf("\nLebron dribbles towards the line ");
System.out.printf("\nKobe has him covered, Lebron takes the fade away shot!");
System.out.printf("\nScore! thats 3 points for Lebron!");
lscore += 3;
PlayKobe();
}
if(shotclock == 3){
System.out.printf("\nLebron is locked down and shaking!");
System.out.printf("\nKobe Steals the ball! ");
PlayKobe();
}
}
}
Currently you have
if(kscore < 22) {
System.out.printf("\nKobe has won the game of 21!");
//Win();
}
Which essentially means your code does nothing besides printing when a player reaches the score limit, you want to add a return statement to go back to your main loop.
You'll also want to check for when the score exceeds 21 and not the opposite.
if(kscore > 21) {
System.out.printf("\nKobe has won the game of 21!");
return;
}
You'll need that for both players ofc.
I'm working on this guessing game for school. I've realized that at some point I deleted my while loop for the user's guess equalling the computer's random number and it has messed up the results of my program. I thought that I could just add a nested while loop, but that hasn't worked. I've been trying to figure this out for hours.
Any ideas how to add something like while (guess == number) to my code and keep it working?
/*
Programming Assignment #3: Guess
Peter Harmazinski
Week 8
Guessing Game
*/
import java.util.*;
public class Guess {
public static final int RANGE = 100;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
boolean again = true;
double guessesDividedByGames = 0;
int maxGuesses = 0;
int numGames = 0;
int numGuesses = 1;
int totalGuesses = 0;
Random rand = new Random();
int number = rand.nextInt(RANGE) + 1;
int guessTracker = 0;
while(again) {
getInstructions();
int guess = getGuess(console);
numGuesses = getHigherLower(guess, number, console);
totalGuesses += numGuesses;
again = playAgain(numGuesses, console);
numGames++;
if (numGuesses > maxGuesses) {
maxGuesses = numGuesses;
}
}
guessesDividedByGames = (double)totalGuesses / numGames;
getResults(numGames, totalGuesses, guessesDividedByGames, maxGuesses);
}
//Prints instructions for user
public static void getInstructions() {
System.out.println("This program allows you to play a guessing game");
System.out.println("I will think of a number between 1 and " + RANGE);
System.out.println("and will allow you to guess until you get it.");
System.out.println("For each guess, I will tell you whether the");
System.out.println("right answer is higher or lower than your guess");
System.out.println("");
}
//Allows the user to play again if first letter of input is "y" or "Y"
public static boolean playAgain(int guessesNum, Scanner console) {
boolean anotherTime = false;
System.out.println("You got it right in " + guessesNum + " guesses.");
System.out.println("");
System.out.print("Do you want to play again? ");
String repeat = console.next();
String[] yesOrNo = repeat.split("");
System.out.println("");
if (yesOrNo[0].equals("y") || yesOrNo[0].equals("Y")) {
anotherTime = true;
}
return anotherTime;
}
//Outputs the results if the user doesn't play again
public static void getResults(int gamesTotal, int guessesTotal, double guessesDividedByGames, int guessesMax) {
System.out.println("Overall results:");
System.out.println("\ttotal games\t= " + gamesTotal);
System.out.println("\ttotal guesses\t= " + guessesTotal);
System.out.println("\tguesses/game\t= " + guessesDividedByGames);
System.out.println("\tmax guesses\t= " + guessesMax);
}
//Tells the user whether the random number is higher or lower
//and then returns the number of guesses
public static int getHigherLower(int guess, int randomNumber, Scanner console) {
int guessIncreaser = 1;
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
return guessIncreaser;
}
//Asks the user to guess the random number
//then returns the guess
public static int getGuess(Scanner console) {
System.out.println("I'm thinking of a number...");
System.out.print("Your Guess? ");
int playerGuess = console.nextInt();
while (playerGuess < 1 || playerGuess > RANGE) {
System.out.println("Out of range, please try again.");
System.out.print("Your Guess? ");
playerGuess = console.nextInt();
}
return playerGuess;
}
}
The problem appears to be your getHigherLower method, specifically these two while blocks:
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
If the user guessed a number lower than randomNumber, then higher, both while blocks would be escaped. Instead, what you want is this:
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
}
else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
What you need is one big while loop not two little ones
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
} else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
First off, I'm hesitant to just give you the answer in code since this is for a school project and we learn by challenging ourselves and actualizing solutions. But I'm willing to point you in the right direction.
1. getHigherLower()
As others have pointed out, your two while loops are set up to cause errors. For instance, if I first guess too low, and then too high, your method mistakenly tells me I guessed correctly. This is a big problem!
Random number = 63
Guess 1 = 34 (lower)
Guess 2 = 100 (higher)
Actually your program tells me my guess of "100" when the number is "63" is correct!
// 1st conditional check: 34 !> 63, so skips first while loop
while (guess > randomNumber) {
guess = getGuess(console);
}
// 1st conditional check: 34 < 63, so enters second while loop
// 2nd conditional check: 100 !< 63, so skips second while loop
while (guess < randomNumber) {
// guess now becomes 100, goes back to top of while loop to check condition again
guess = getGuess(console);
}
// returns and exits method here (program wrongly thinks user has guessed correctly!)
Note that you can do a
System.out.println("random number: " + number);
to test that you're actually guessing the random number correctly. You might look into some JUnit testing as well.
James Ko seems to have a good feel for a better method implementation.
2. playAgain()
You use an if statement to check if the first index in an array of strings equals "y" or "Y" but your program never continues. Why is this?
if (yesOrNo[?].equals("y") {
anotherTime = true;
}
You should consider whether user input is really being placed at the first index or not?
Hint: loop through the "yesOrNo" array and print out each index to see where the user input is being placed in the array.
for (int i = 0; i < yesOrNo.length; i++) {
System.out.println("String at index " + i + ": " + yesOrNo[i]);
}
Good luck and remember that testing is your friend!
Please help with the swtich case need for a game
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please Enter a number");
int day = input.nextInt();
switch(day)
{
case 1: System.out.println("1 Microphone");
break;
case 2: System.out.println("2 Loud Speakers 1 Microphone ");
break;
case 3: System.out.println("3 Keyboards 2 Loudspeakers 1 Microphone ");
break;
case 4: System.out.println("4 Java Books 3 Keyboards 2 Loudspeakers 1 Microphone");
break;
case 5: System.out.println("5 Iphones 4 Java Books 3 Keyboards 2 Loudspeakers 1 Microphone");
break;
default: System.out.println("Enter A Valid Prize Day");
}
}
As #AlexandreSantos pointed out, you need to reinitialise the values of maxRolls and sum every time you restart the game. That is, these initialisations should be the first things executed in your do {} while () loop.
do {
int maxRolls = 7;
int sum = 0;
// ...
} while (option);
I'd also give you other recommendations:
in Java, the class names, by convention, start with an upper-case letter. Thus, I'd name your class Game instead of game.
The following code (and its equivalent with "no"):
(userInputTwo.equals("Yes") || userInputTwo.equals("yes") || userInputTwo.equals("YES"))
... can be replaced by:
userInputTwo.equalsIgnoreCase("yes")
... since, as you mentioned in your question, you're actually simply trying to ignore the case ;)
You're doing all that asking the user whether is wants to restart or not in two places. You could (should) actually simply do it once, after having printed either "You won" or "You lost".
I'd suggest to replace:
if (sum >= 43) {
System.out.println("You Win");
System.out.print("Would You Like To Play Again . Yes or No?");
final String userInput = input.nextLine();
if (userInput.equals("Yes") || userInput.equals("yes") || userInput.equals("YES")) {
// MISSING CODE TO RESTART THE PROGRAM
option = true;
} else if (userInput.equals("No") || userInput.equals("no") || userInput.equals("NO")) {
System.exit(0);
}
}
if (sum < 43 || sum % 10 == 0) {
System.out.println("You Lose");
System.out.print("Would You Like To Play Again . Yes or No?");
final String userInputTwo = input.nextLine();
if (userInputTwo.equals("Yes") || userInputTwo.equals("yes") || userInputTwo.equals("YES")) {
option = true;
// MISSING CODE TO RESTART THE PROGRAM
} else if (userInputTwo.equals("No") || userInputTwo.equals("no") || userInputTwo.equals("NO")) {
System.exit(0);
}
}
... by:
if (sum >= 43) {
System.out.println("You Win");
}
if (sum < 43 || sum % 10 == 0) {
System.out.println("You Lose");
}
System.out.print("Would You Like To Play Again . Yes or No?");
final String userInput = input.nextLine();
if ("yes".equalsIgnoreCase(userInput) {
// MISSING CODE TO RESTART THE PROGRAM
option = true;
} else if ("no".equalsIgnoreCase(userInput)) {
System.exit(0);
}
... or, even better, extracting this into an other method.
Or, even better, not even checking for one of the possibilities and make it the default one, in case the user enters something that's neither "yes" nor "no":
private static boolean restart(final Scanner input) {
// I choose to interpret any input that's different from "yes" as a "no".
System.out.print("Would You Like To Play Again. Yes or No? (default: No)");
final String userInput = input.nextLine();
if ("yes".equalsIgnoreCase(userInput)) {
return true;
}
return false;
}
... which can obviously then become:
private static boolean restart(final Scanner input) {
// I choose to interpret any input that's different from "yes" as a "no".
System.out.print("Would you like to play again? [Yes/No] (default: No)");
return "yes".equalsIgnoreCase(input.nextLine());
}
... and the option variable could disappear:
do {
...
} while (Game.restart(input));
You could (should) use Random instead of Math.random(), it's just way more convenient.
For example:
final int dieOne = (int) (Math.random() * faces) + 1;
final int dieTwo = (int) (Math.random() * faces) + 1;
final int totalRollForRound = dieOne + dieTwo;
... could become:
// Outside of the do {} while ():
final Random r = new Random();
// Inside the do {} while ():
final int totalRollForRound = r.nextInt(faces) + r.nextInt(faces) + 2;
You should always close the Scanner before leaving the program.
Use the try-with-resources syntax:
private static boolean restart() {
try (final Scanner input = new Scanner(System.in) {
// I choose to interpret any input that's different from "yes" as a "no".
System.out.print("Would you like to play again? [Yes/No] (default: No)");
return "yes".equalsIgnoreCase(input.nextLine());
}
}
One last thing: your sum % 10 == 0 is weird: you've already told the user that he won if he scored at least 43, and he's gonna lose if he scored less than 43... You should either:
Test that condition before checking whether the user has scored more than 43 (and therefore also rejecting scores like 50, 60, 70, 80...)
... or:
Forget about that rule that only aims to reject 10, 20, 30 and 40, which are already covered by the score < 43 rule.
Cheers ;)
Just 'cause I felt bored, I actually applied my own advices (and a few more) to your code:
import java.util.Random;
import java.util.Scanner;
public class Game {
private static final int FACES = 6;
private static final int MAX_ROLLS = 7;
private static final Random R = new Random();
public static void main(final String[] args) {
try (final Scanner input = new Scanner(System.in)) {
do {
if (Game.roll() >= 43) {
System.out.println("You won!");
} else {
System.out.println("You lost.");
}
} while (Game.restart(input));
}
}
private static int roll() {
int maxRolls = MAX_ROLLS;
int sum = 0;
for (int i = 1; i < maxRolls; i++) {
final int dieOne = R.nextInt(FACES) + 1;
final int dieTwo = R.nextInt(FACES) + 1;
sum += dieOne + dieTwo;
System.out.println("Roll #" + i + ": You rolled " + dieOne + " and " + dieTwo + ".\tYour new total is: " + sum);
if (dieOne == dieTwo) {
System.out.println("DOUBLES! You get an extra roll.");
maxRolls++;
}
}
return sum;
}
private static boolean restart(final Scanner input) {
System.out.print("Play again? [Yes/No] (default: No): ");
return "yes".equalsIgnoreCase(input.nextLine());
}
}
Sounds like you want an outer loop; each time through the loop the user plays one game. At the top of that loop, you initialize the values that you need to play one game:
boolean playingMoreGames = false;
do
{
int sum = 0;
int maxRolls = 6;
int rollsMade = 0;
boolean gameOver = false;
do
{
// roll dice
// determine win or loss
// and determine whether game is over
// include testing rollsMade against maxRolls
}
while (!gameOver)
// ask user whether he wants to play again and set playingMoreGames accordingly
}
while (playingMoreGames);
I have suggested a change to a while loop that executes as long as the maxRolls has not been reached. It is not a good idea to modify the target of a for loop within the loop; in some languages, at least, the behavior is undefined, and it confuses the reader. Since maxRolls can change, you need a different looping form there.
And you don't really need to call System.exit(); if you "fall out of" the bottom of your main routine, your program will just exit since it has no more instructions to execute.
I don't recommend do while(true) in this case; the (small) problem with it is that it makes it harder for the reader to determine when the loop exits. Not a big deal.
Good luck.