I'm trying to implement a DiceThrowingGame which works fine. I have 2 classes currently which are "Player" and "Game". The code for the Game class is as below:
package dice.throwing.game;
import java.util.Scanner;
public class Game {
private int winningPoints;
private Player player1, player2;
private boolean gameSetup;
private final String defaultWinningScore = "200";
public Game() {
this.setWinningPoints(200);
this.gameSetup = false;
}
private int readScore(Scanner scanner) {
String score = "";
try {
score = scanner.nextLine();
if (score.isEmpty()) {
score = this.defaultWinningScore;
}
} catch (Exception e) {
}
return Integer.parseInt(score);
}
private Player createPlayer(Scanner scanner) {
String name = null;
do {
try {
name = scanner.nextLine();
if (name.isEmpty()) {
System.err.println("Name cannot be empty. Try again: ");
}
} catch (Exception e) {
}
} while (name.isEmpty());
return new Player(name);
}
private void startGame(Scanner scanner) {
System.out.println("Enter first player's name: ");
player1 = createPlayer(scanner);
System.out.println("Enter second player's name: ");
player2 = createPlayer(scanner);
System.out.println("Maximum score to win (<Enter> to use default 200): ");
this.setWinningPoints(this.readScore(scanner));
this.gameSetup = true;
}
private void playOneRound() {
int p1r1, p1r2, p2r1, p2r2;
p1r1 = (int) (1 + ((Math.random() * 10) % 6));
p1r2 = (int) (1 + ((Math.random() * 10) % 6));
p2r1 = (int) (1 + ((Math.random() * 10) % 6));
p2r2 = (int) (1 + ((Math.random() * 10) % 6));
int p1Points, p2Points;
boolean p1Bonus = false, p2Bonus = false;
p1Points = p1r1 + p1r2;
p2Points = p2r1 + p2r2;
if (p1r1 == p1r2) {
p1Points *= 2;
p1Bonus = true;
}
if (p2r1 == p2r2) {
p2Points *= 2;
p2Bonus = true;
}
player1.setTotalPoints(player1.getTotalPoints() + p1Points);
player2.setTotalPoints(player2.getTotalPoints() + p2Points);
System.out.print(player1.getName() + " rolled " + p1r1 + " + " + p1r2 + ", and scored " + p1Points + " points");
if (p1Bonus)
System.out.println(" (BONUS!)");
else
System.out.println();
System.out.print(player2.getName() + " rolled " + p2r1 + " + " + p2r2 + ", and scored " + p2Points + " points");
if (p2Bonus)
System.out.println(" (BONUS!)");
else
System.out.println();
}
private void leaderBoard() {
int p1Points = player1.getTotalPoints();
int p2Points = player2.getTotalPoints();
if (p1Points == p2Points)
System.out.println("Both players have the same score (" + p1Points + ") at the moment");
else {
System.out.print(player1.getName() + "'s current score is " + p1Points);
if (p1Points > p2Points)
System.out.println(" <--- CURRENT LEADER!");
else
System.out.println();
System.out.print(player2.getName() + "'s current score is " + p2Points);
if (p1Points < p2Points)
System.out.println(" <--- CURRENT LEADER!");
else
System.out.println();
}
}
private void gameHelp() {
System.out.println("<ENTER SOME HELP TEXT HERE>");
}
private boolean isGameOver() {
int player1Points = player1.getTotalPoints();
int player2Points = player2.getTotalPoints();
if(player1Points == player2Points &&
player1Points > this.winningPoints) {
System.out.println("Game Over! It's a draw!");
return true;
} else if(player1Points > this.winningPoints && player1Points > player2Points) {
System.out.println("Game Over! " + player1.getName() + " is the winner!");
return true;
} else if(player2Points > this.winningPoints && player2Points > player1Points) {
System.out.println("Game Over! " + player2.getName() + " is the winner!");
return true;
}
return false;
}
private void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
while (!exit) {
System.out.println("Welcome to my Dice-and-Roll Game!");
System.out.println("==============================");
System.out.println("(1) Start a new game");
System.out.println("(2) Play one round");
System.out.println("(3) Who is leading now?");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 5) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
if (!this.gameSetup && (choice == 2 || choice == 3)) {
System.err.println("Error : Players have not been setup");
choice = 0;
}
switch (choice) {
case 1:
this.startGame(scanner);
break;
case 2:
this.playOneRound();
break;
case 3:
this.leaderBoard();
break;
case 4:
this.gameHelp();
break;
case 5:
exit = true;
}
if(this.gameSetup && this.isGameOver()) {
System.out.println("Exiting now.. See you later!");
exit = true;
}
}
scanner.close();
}
public static void main(String[] args) {
Game game = new Game();
game.eventLoop();
}
public int getWinningPoints() {
return winningPoints;
}
public void setWinningPoints(int winningPoints) {
this.winningPoints = winningPoints;
}
}
But I want to move the DiceThrowing part of the code to another class called "Dice" which is this part:
private void playOneRound() {
int p1r1, p1r2, p2r1, p2r2;
p1r1 = (int) (1 + ((Math.random() * 10) % 6));
p1r2 = (int) (1 + ((Math.random() * 10) % 6));
p2r1 = (int) (1 + ((Math.random() * 10) % 6));
p2r2 = (int) (1 + ((Math.random() * 10) % 6));
Confused on whether to put the whole playOneRound() method or just the Math.Random line?
To keep responsibilities and abstractions separate:
I would have a method Dice.getNumber() which would return the result of
(int) (1 + ((Math.random() * 10) % 6));
You could also have a 2nd method that would return an array of dice throws with a nbOfThrows parameter.
Then the playOneRound() would involve the throw of the dice as many times as the games rules allow.
Related
If someone presses e, I want my game to stop at any time in the game.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time! ");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
int theAnswer = input.nextInt();
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}
Instead of just "int theAnswer = input.nextInt();" write this:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equal("e")) {
System.out.println("Exiting the game...")
break;
}
else {
theAnswer = Integer.parseInt(nextIn);
}
I obviously haven't accounted for exceptions, but you can if you want.
So altogether it looks like this:
public class Game{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time!");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
//new part:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equals("e")) {
System.out.println("Exiting the game...")
break;
} else {
theAnswer = Integer.parseInt(nextIn);
}
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}
So for yet ANOTHER project I am doing an RPG code. Like Dungeons and dragons. My particular problem is the attributes. Basically the application gives statistics to the player and then, in case the player does not like the stats they have recieved, the application gives them the option to reroll. The first roll does fine, however, if the user chooses to reroll, the stats (both the first and the next) add on to each other. Here is my code:
The Main Method:
package bagOfHolding;
public class Advanced {
public static void main(String [] args){
GameMaster.game();
}
}
The Dice Class (this rolls the stats for the statistics):
package bagOfHolding;
import java.util.Random;
public class DiceBag {
private static int sum;
public static int rollD6() {
int[] Dice = new int[3];
Random num = new Random();
for (int i = 0; i < Dice.length; i++) {
Dice[i] = num.nextInt((6)) + 1;
}
for (int i : Dice) {
sum += i;
}
return sum;
}
// public static int getSum() {
// return sum;
// }
// public static void setSum(int sum) {
// DiceBag.sum = sum;
// }
}
The Game Master (This does the whole game):
package bagOfHolding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GameMaster {
public static void game() {
Hero.attributes();
}
public static void ReRoll() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Would you like to reroll your hero? 1) Yes or 2) No");
System.out.println("Please enter a number");
System.out.println("Any number other than 1 or 2 will exit the application");
try {
String userInput = delta.readLine();
int input = Integer.parseInt(userInput);
if (input == 1) {
Hero.setStrength(DiceBag.rollD6());
Hero.setDexterity(DiceBag.rollD6());
Hero.setIntelligence(DiceBag.rollD6());
Hero.attributes();
} else if (input == 2) {
System.exit(0);
} else {
System.exit(0);
}
} catch (NumberFormatException NFE) {
System.out.println("Invalid");
} catch (IOException IOE) {
System.out.println("Invalid");
}
}
}
And the Hero class (this has all the statistics):
package bagOfHolding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Hero {
/*
* Attributes - Randomly determined by 3d6
*
*/
/*
* -3 attributes - Strength - Damage bonus - If over 15 every pt = +1 (_++;)
* - Negative Damage Bonus - If under 10 every pt = -1 (_--;) - Dexterity
* -Strike bonus - every 2 pts over 14 = (_%2 + 1) - Negative Strike bonus -
* every 2 pts below 10 = (_%2 -1) - Dodge bonus - every 2 pts over 15 =
* (_%2 + 1) - Negative dodge bonus - every 2 pts below 11 = (_%2 -1) -
* Intelligence -Spell Strength Bonus - every pt over 15 = (++2) - Negative
* Spell Strength Bonus - every pt below 11 = (--2)
*
* Base Attributes - Health -Strength * 10 - MP - Intelligence *5
*/
private static int strength = DiceBag.rollD6();
private static int intelligence = DiceBag.rollD6();
private static int dexterity = DiceBag.rollD6();
public static int getIntelligence() {
return intelligence;
}
public static void setIntelligence(int intelligence) {
Hero.intelligence = intelligence;
}
public static int getDexterity() {
return dexterity;
}
public static void setDexterity(int dexterity) {
Hero.dexterity = dexterity;
}
public static int getStrength() {
return strength;
}
public static void setStrength(int strength) {
Hero.strength = strength;
}
public static void attributes() {
strength = getStrength();
System.out.println("Here is your hero: ");
// DiceBag.rollD6();
System.out.println("Strength = " + strength);
if (strength > 15) {
System.out.println("Damage Bonus = " + "+" + (strength - 15));
} else if (strength < 10) {
System.out.println("Negative Damage Bonus = " + "-" + (10 - strength));
} else {
System.out.println("You do not have damage bonus");
}
intelligence = getIntelligence();
System.out.println("Intelligence = " + intelligence);
if (intelligence > 15) {
System.out.println("Spell Strength Bonus = " + "+" + ((intelligence - 15) * 2));
} else if (strength < 11) {
System.out.println("Negative Spell Strength Bonus = " + "-" + ((11 - intelligence) * 2));
} else {
System.out.println("You do not have a spell strength bonus");
}
dexterity = getDexterity();
System.out.println("Dexterity = " + dexterity);
if (dexterity > 15 && dexterity % 2 == 0) {
System.out.println("Dodge Bonus = " + "+" + (dexterity - 15));
} else if (dexterity < 11 && dexterity % 2 == 0) {
System.out.println("Negative Dodge Bonus = " + "-" + (11 - dexterity));
} else {
System.out.println("You do not have a dodge bonus");
}
if (dexterity > 14 && dexterity % 2 == 0) {
System.out.println("Strike Bonus = " + "+" + (dexterity - 14));
} else if (dexterity < 10 && dexterity % 2 == 0) {
System.out.println("Negative Strike bonus = " + "-" + (10 - dexterity));
} else {
System.out.println("You do not have a strike bonus");
}
int health = strength * 10;
System.out.println("Health = " + health);
int MP = intelligence * 5;
System.out.println("MP = " + MP);
GameMaster.ReRoll();
}
}
DiceBag sum should be local to rollD6 rather than static.
I've been working on a java project for me class, and I am almost done. the program is a hangman game, where the user inputs a letter, and the program continues depending whether the letter is in the word or not. The issue I am having is that I cannot figure out how to make it so when the user enters more than one letter, a number or a symbol, the program prints out a statement that says "Invalid input, try again" and has the user input something again, instead of showing it to be a missed try or the " letter" not being in the word. Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println();
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
System.out.println("Choose a letter: ");
letter = game.in.next();
if(letter.length() == 1)
{
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}else
{
System.out.println("Invalid input, try again");
}
You can use a regular expression to check the input.
if (!letter.matches("[a-zA-Z]{1}")) {
System.out.println("Invalid Input") {
else {
<your other code>
}
Try this,
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
String input = in.readLine();
if(input.length() == 1){
game.puzzles[count] = ; //get line of data
count++; //Increment CWID counter
}
else{
System.out.println("INVALID INPUT");
}
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println();
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
You can use String.length() for checking the length of the input, e.g. in your case
if(letter.length() != 1) {
// do something to handle error
}
String.length() can be used to determine, if the input has one letter. To check if the read String is a letter you can use Character.isLetter(char):
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
String line = null;
while (in.ready()) { //while there is another line in the input file
line = in.readLine();
if (line.length() == 1 && Character.isLetter(line.charAt(0)) {
game.puzzles[count] = line; //get line of data
count++; //Increment CWID counter
} else {
// handle the else-case
}
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
afer program outputs a winner, i ask if user wants to play again or exit but for some reason scanner doesn't read this input(continue or not). I even put prompt for continuation outside the while loop but still no luck:
"|XXX|
| O |
| O|
Player X is a winner!
Do you want to play again? Enter Y for yes or N for no!
BUILD SUCCESSFUL (total time: 26 seconds)
"
This is code:
public class TicTacToeRunner
{
public static void main(String[] args)
{
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
while (!done)
{
do
{
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) //check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) //if entered -1 quit the game
{
done = true;
System.out.println("Player " +player.toUpperCase() + " ended the game !");
System.exit(0); //game termination
}
else
{
System.out.print("Column for " + player.toUpperCase() + ": ");
if(in.hasNextInt()) //check if input is an integer
{
column = in.nextInt();
}
}
}while(!game.checkForValidMove(row, column)); //end of do-while loop if checkForValidMove is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) //check wins after 5 moves
{
if (game.checkForWin(row, column, player)) //if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) //Check for ties after 7 moves
{
if (game.checkForEarlyTie()) //check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X"))
{
player = "O";
}
else
{
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
answer = in.nextLine();
answer = answer.toLowerCase(); //change input to lowercase for bullet proofing
if(answer.equals("y"))
{
done = false;
player = "X";
moveCounter = 0;
game.resetTheGame();
}
else
{
System.exit(0); //program termination
}
}
}
using a do while loop. your work is easy..
import java.util.Scanner;
public class TicTacToeRunner {
public static void main(String[] args) {
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
String choice = "";
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
do{
while (!done) {
do {
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) // check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) // if entered -1 quit the game
{
done = true;
System.out.println("Player " + player.toUpperCase() + " ended the game !");
System.exit(0); // game termination
} else {
System.out.print("Column for " + player.toUpperCase() + ": ");
if (in.hasNextInt()) // check if input is an integer
{
column = in.nextInt();
}
}
} while (!game.checkForValidMove(row, column)); // end of do-while
// loop if
// checkForValidMove
// is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) // check wins after 5 moves
{
if (game.checkForWin(row, column, player)) // if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) // Check for ties after 7 moves
{
if (game.checkForEarlyTie()) // check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X")) {
player = "O";
} else {
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
choice = in.nextLine();
}while(choice.equals("y")||choice.equals("Y"));
}
}
How do i return an error and ask the question Do you want to try again (Y/N)? again when the user entered neither Y/N as an answer?
package randomgenerate;
/**
*
* #author Trung
*/
public class World {
public static void main(String[] args) {
int max=0;
int min=0;
double aver = 0;
int option;
rg a = new rg();
a.generate();
a.count();
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
switch (option)
{
case 1:
{
a.generate();
a.count();
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
}
case 2:
{
System.out.println("Program exits.");
System.exit(0);
}
case 3:
{
System.out.println("Invalid. Please enter gyh or gnh: ");
a.getchoice();
}
}
}
}
package randomgenerate;
import java.util.Scanner;
/**
*
* #author Trung
*/
public class rg {
//generate 100 random number
int s[]= new int[101];
public void generate (){
int i, random;
System.out.println("Generating 100 random integers between 0 and 9");
for (i=1; i<=100;i++)
{
s[i] = (int)(Math.random()*10+0);
System.out.println("Number "+i+" = "+ s[i]);
}
}
//count
public void count (){
int i;
int count0=0;
int count1=0;
int count2=0;
int count3=0;
int count4=0;
int count5=0;
int count6=0;
int count7=0;
int count8=0;
int count9=0;
for (i=1; i<=100; i++)
{
if (s[i]==0)
{
count0++;
}
else if (s[i]==1)
{
count1++;
}
else if (s[i]==2)
{
count2++;
}
else if (s[i]==3)
{
count3++;
}
else if (s[i]==4)
{
count4++;
}
else if (s[i]==5)
{
count5++;
}
else if (s[i]==6)
{
count6++;
}
else if (s[i]==7)
{
count7++;
}
else if (s[i]==8)
{
count8++;
}
else if (s[i]==9)
{
count9++;
}
}
if (count0 <= 1)
{
System.out.println("0 occurs "+ count0 + " time");
}
else
{
System.out.println("0 occurs "+ count0 + " times");
}
if (count1 <= 1)
{
System.out.println("1 occurs "+ count1 + " time");
}
else
{
System.out.println("1 occurs "+ count1 + " times");
}
if (count2 <= 1)
{
System.out.println("2 occurs "+ count2 + " time");
}
else
{
System.out.println("2 occurs "+ count2 + " times");
}
if (count3 <= 1)
{
System.out.println("3 occurs "+ count3 + " time");
}
else
{
System.out.println("3 occurs "+ count3 + " times");
}
if (count4 <= 1)
{
System.out.println("4 occurs "+ count4 + " time");
}
else
{
System.out.println("4 occurs "+ count4 + " times");
}
if (count5 <= 1)
{
System.out.println("5 occurs "+ count5 + " time");
}
else
{
System.out.println("5 occurs "+ count5 + " times");
}
if (count6 <= 1)
{
System.out.println("6 occurs "+ count6 + " time");
}
else
{
System.out.println("6 occurs "+ count6 + " times");
}
if (count7 <= 1)
{
System.out.println("7 occurs "+ count7 + " time");
}
else
{
System.out.println("7 occurs "+ count7 + " times");
}
if (count8 <= 1)
{
System.out.println("8 occurs "+ count8 + " time");
}
else
{
System.out.println("8 occurs "+ count8 + " times");
}
if (count9 <= 1)
{
System.out.println("9 occurs "+ count9 + " time");
}
else
{
System.out.println("9 occurs "+ count9 + " times");
}
}
public int maximum (int max)
{
max = s[0];
for (int i=1;i<=100;i++)
{
if(max<s[i])
{
max=s[i];
}
}
return (max);
}
public int minimum (int min)
{
min = s[0];
for (int i=1;i<=100;i++)
{
if(s[i]<min)
{
min=s[i];
}
}
return (min);
}
public double average (double aver)
{
int i = 1;
int subtotal1 = 0;
int subtotal2 = 0;
int subtotal3 = 0;
int subtotal4 = 0;
int subtotal5 = 0;
int subtotal6 = 0;
int subtotal7 = 0;
int subtotal8 = 0;
int subtotal9 = 0;
for (i=1;i<=100;i++)
{
if (s[i]==1)
{
subtotal1 = subtotal1 + s[i];
}
else if (s[i]==2)
{
subtotal2 = subtotal2 +s[i];
}
else if (s[i]==3)
{
subtotal3 = subtotal3 +s[i];
}
else if (s[i]==4)
{
subtotal4 = subtotal4 +s[i];
}
else if (s[i]==5)
{
subtotal5 = subtotal5 +s[i];
}
else if (s[i]==6)
{
subtotal6 = subtotal6 +s[i];
}
else if (s[i]==7)
{
subtotal7 = subtotal7 +s[i];
}
else if (s[i]==8)
{
subtotal8 = subtotal8 +s[i];
}
else if (s[i]==9)
{
subtotal9 = subtotal9 +s[i];
}
}
aver = (subtotal1 + subtotal2 + subtotal3 + subtotal4 + subtotal5 + subtotal6 + subtotal7 + subtotal8 + subtotal9) * 0.01;
return (aver);
}
public int getchoice() {
Scanner reader = new Scanner(System.in);
String selection = reader.nextLine();
if (selection.equals("y") || selection.equals("Y")){
return 1;
}
else if (selection.equals("n") || selection.equals("N")){
return 2;
}
else
{
return 3;
}
}
}
Try something like this:
while(true){
System.out.println("Do you want to try again (Y/N)?");
String input = reader.nextLine();
if(input.equals("N"))
break;
else
continue;
}
you can just add in the getchoice() method :
if(!selection.toLowerCase().equals("y") && !selection.toLowerCase().equals("n") ){
System.out.println("Error");
return this.getchoice();
}
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to run it again (y/n)?: ");
while (!(sc.hasNext() && ((sc.nextLine().equalsIgnoreCase("y"))||
sc.nextLine().equalsIgnoreCase("n")))){
System.out.println("Do you want to run it again (y/n)?: ");
// other code
}
Firstly, refactor the code into a method. Then you can call the method anywhere in your program (currently, you call it twice, so you can replace both versions with this version.
Then, add a loop...
public static int getRunAgain(rg a) {
int option = 3;
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
while(true) {
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
if (option != 3) break;
System.out.println("Invalid. Please enter y/n. ");
}
return option;
}
An alternative method would be to put the loop inside the getChoice method.
do
{
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
}while(option.equals("Y") || !option.equals("N"));
If user enters Y, it will repeat. Aslo, if he enters neither "Y" nor "N", then it will repeat too.