The code compiles without any issue, then I enter 0 it plays, then when entering X, it crashes with the error in set(playerVal, scan.nextInt());
public static void main(String[] args) {
createBoard(3,3);
int turn = 0;
int playerVal;
int outcome;
java.util.Scanner scan = new
java.util.Scanner(System.in);
do {
displayBoard();
playerVal = (turn % 2 == 0)? NOUGHT : CROSS;
if (playerVal == NOUGHT) {
System.out.println ("\n-0's turn-");
} else {
System.out.println("\n-X's turn-");
}
System.out.print("Enter row and Column:");
try {
set(playerVal, scan.nextInt());
} catch (IllegalArgumentException ex)
{System.err.println(ex);}
turn ++;
outcome = winOrTie();
} while ( outcome == -2 );
displayBoard();
switch (outcome) {
case NOUGHT:
System.out.println("0 wins!");
break;
case CROSS:
System.out.println("X wins!");
break;
case 0:
System.out.println("Tie.");
break;
}
}
}
Be able to play the game when entering the 0 and X.
Related
I'm trying to make a simple BlackJack game driven by character input and I'm having a lot of problems in the later part it.
I commented the part that's giving me troubles, the rest doesn't seem to have errors and I did unit test it.
So, what did I do? I created a class that holds the cards drawn and manages them, table, player and dealer are both instances of table.
A table has max 5 cards(for simplicity), every card object comes from the Card class that has a method to add data to the card object.
The main class drives the program and the decisions are made with a character input from the keyboard, I get problems at that point.
import java.io.IOException;
class Table{
Card[] hand = new Card[5];
int counter = 1;
Table() {
for ( int i=0; i<hand.length; i++) {
hand[i]=new Card();
}
hand[0].GetCard();
}
void ReadCards(){
for(int i= 0;i<counter;i++ ) {
System.out.println("The card "+(i+1)+" is " + hand[i].name + " "+ hand[i].seed + "." );
}
}
void DrawCards() {
hand[counter].GetCard();
counter++;
}
boolean isOut() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
if(sum >21) {
return true;
}
}
return false;
}
int TheSum() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
return sum;
}
boolean isWIN(Table p2) {
int sum = 0;
int sump2 = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
for(int i= 0;i<p2.counter;i++ ) {
sump2 += p2.hand[i].value;
}
if (sum>sump2) {
return true;
}
else return false;
}
class Card {
public int value = 0;
public String name = "";
public String seed = "";
void GetCard(){
int positive = 0;
do {
positive = (int) (Math.random()*100) % 10;
}while(positive == 0 );
value = positive;
if(value<10) {
name = String.valueOf(value);
}
else {
positive = 0;
do {
positive = (int) (Math.random()*100) % 3;
}while(positive == 0 );
switch(positive) {
case 1:
name = "J";
break;
case 2:
name = "Q";
break;
case 3:
name ="K";
break;
}
}
positive = 0;
do {
positive = (int) (Math.random()*100) % 4;
}while(positive == 0 );
switch(positive) {
case 1:
seed = "CLUB";
break;
case 2:
seed = "DIAMOND";
break;
case 3:
seed ="SPADE";
break;
case 4:
seed ="HEART";
break;
}
}
}
}
public class BlackJack {
public static void main(String args[])throws IOException {
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char)System.in.read();
}while(flag != 'y' );
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
/*
flag = (char)System.in.read();
while(flag != 'n' ) {
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
flag = (char)System.in.read();
}
System.out.println("The dealer will draw");
while(dealer.TheSum()<18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
*/
System.out.println("WHO WON?");
if (player.isWIN(dealer)){
System.out.println("YOU WIN");
}
else System.out.println("YOU LOSE");
}
}
And yes, I'm not used to java.
Console screenshot of the output here!
Here is an example of fixing your looping issues, however there may be some issue with the game logic, which is out of the scope of this question.
public static void main(String args[]) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char) s.nextLine().charAt(0);
} while (flag != 'y');
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
while (true) {
flag = s.nextLine().charAt(0);
if (flag == 'n') {
break;
}
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
System.out.println("The dealer will draw");
while (dealer.TheSum() < 18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
System.out.println(String.format("The dealer has finished drawing. Dealers score %d. Your score %d", dealer.TheSum(), player.TheSum()));
}
System.out.println("WHO WON?");
if (player.isWIN(dealer)) {
System.out.println("YOU WIN");
} else {
System.out.println("YOU LOSE");
}
}
Output:
Welcome to the BlackJack's table! Press y to start!
y
DEALER
The card 1 is 8 CLUB.
PLAYER
The card 1 is 2 SPADE.
Do you want to draw a card? I'll draw until you'll press n
n
WHO WON?
YOU LOSE
I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.
So, I'm working on this assignment for a class. It's a Java class, and I'm supposed to make a game where it rolls two dice, adds them up, and adds them to your turn score. It then asks if you want to keep playing. When your turn score hits 20, or when you decide to pass, it goes to a computer. It's supposed to print the scores each turn, and then when someone hits 100 points, it announces the winner. However, no matter what, the score at the end of each turn is 0, no matter how many times I run it. When a player rolls a 1, their turn score is cancelled, and it moves on to the other player, and if they roll double 1's, they lose all of their points for the game so far. Here is my code, can you figure out why the score variables don't update? Thank you.
import java.util.Scanner;
import java.util.Random;
public class PlayPig {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int player1 = 0;
int player2 = 0;
int a, b, c, player1turn, player2turn, input;
int pig = 1;
Random r = new Random();
do{
do {
player1turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player1=0;
break;}
else if (a==1 || b==1){
player1turn=0;
break;}
else {
player1turn= a+b ;
}}
player1= player1+player1turn;
System.out.println("Player1 score is " + player1 + " and player2 score is " + player2);
System.out.print("Do you want to keep playing? Enter 1 to continue. Enter any other number to pass.");
input = scan.nextInt();
if (input != 1)
break;
}
while
(player1turn <= 20);
do{
player2turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player2=0;
break;}
else if (a==1 || b==1){
player2turn=0;
break;}
else {
player1turn= a+b ;
player2= player2+player2turn;}}
}
while
(player2turn<=20);
}
while
(player1 < 100 || player2 < 100);
if (player1>player2)
System.out.print("Player 1 wins");
else
System.out.print("Player 2 wins");
}}
The main problem was, that your else conditions in which you assigned the current score were in the wrong block. (These ones):
else {
player1turn = a+b ;
}
Try this code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int player1 = 0;
int player2 = 0;
int a, b, c, player1turn, player2turn, input;
int pig = 1;
Random r = new Random();
do{
do {
player1turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player1 = 0;
break;
}
else if (a==1 || b==1){
player1turn=0;
break;
}
}else {
player1turn = a+b ;
}
player1 += player1turn;
System.out.println("Player1 score is " + player1 + " and player2 score is " + player2);
System.out.print("Do you want to keep playing? Enter 1 to continue. Enter any other number to pass.");
input = scan.nextInt();
if (input != 1){
break;
}
} while (player1turn <= 20);
do{
player2turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player2=0;
break;
} else if (a==1 || b==1){
player2turn=0;
break;
}
}else {
player2turn = a+b ;
player2 += player2turn;
}
}while (player2turn<=20);
} while (player1 < 100 || player2 < 100);
if (player1>player2)
System.out.print("Player 1 wins");
else
System.out.print("Player 2 wins");
}
I have modified the if loop.
You can try this:
import java.util.Scanner;
import java.util.Random;
public class PlayPig {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int player1 = 0;
int player2 = 0;
int a, b, c, player1turn, player2turn, input;
int pig = 1;
Random r = new Random();
do{
do {
player1turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if (a == 1 && b == 1){
player1=0;
break;
}
else if((a== 1 && b!= 1) || (a!=1 && b== 1){
player1turn=0;
break;
}
else{
player1turn= a+b ;
}
player1= player1+player1turn;
System.out.println("Player1 score is " + player1 + " and player2 score is " + player2);
System.out.print("Do you want to keep playing? Enter 1 to continue. Enter any other number to pass.");
input = scan.nextInt();
if (input != 1)
break;
}
while
(player1turn <= 20);
do{
player2turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if (a == 1 && b == 1){
player2=0;
break;
}
else if((a== 1 && b!= 1) || (a!=1 && b== 1){
player2turn=0;
break;
}
else{
player2turn= a+b ;
}
player2= player2+player2turn;
}
while
(player2turn<=20);
}
while
(player1 < 100 || player2 < 100);
if (player1>player2)
System.out.print("Player 1 wins");
else
System.out.print("Player 2 wins");
}}
First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.
I tried making a menu system to make a user select between four options. To distinguish between the selections I check the int entered. It works but somehow I feel it is not very elegant. Especially when I set the initial value of selectedMenu to 1902475424 to check for when the user entered a mismatcing value. I assumed the user wont accidentally type 1902475424.
Is there a way more simple way to make a menu system or will this do? Is this major flawed?
Yes im a beginner to Java :-)
import java.util.Scanner;
import java.util.InputMismatchException;
public class Menu {
public void printMenu() {
System.out.println(
"1. Start new game\n" +
"2. Load game\n" +
"3. Settings\n" +
"4. Exit\n"
);
}
public void selectMenu() throws InputMismatchException {
int selectedMenu = 1902475424;
Scanner aScanner = new Scanner(System.in);
do {
selectedMenu = 1902475424;
try {
System.out.println("Try block begin.");
selectedMenu = aScanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Catch blok begin.");
System.out
.println("Invalid input, please input a number between 1-4.");
aScanner.nextLine();
}
if ((selectedMenu < 1 || selectedMenu > 4)
&& (selectedMenu != 1902475424)) {
System.out.println("Input out of range \"" + selectedMenu
+ "\". Input a number between 1-4.");
}
} while (selectedMenu == 1902475424
|| (selectedMenu < 1 || selectedMenu > 4));
if (selectedMenu >= 1 && selectedMenu <= 4) {
System.out.println("A new game will now start.");
}
}
}
Your method is leaning into the overkill category :]You can do away with your random value of 1902475424 like so:
public void selectMenu() throws InputMismatchException {
int selectedMenu;
Scanner aScanner = new Scanner(System.in);
do {
try {
System.out.println("Try block begin.");
selectedMenu = aScanner.nextInt();
if(selectedMenu < 1 || selectedMenu > 4) {
System.out.println("Input out of range \"" + selectedMenu + "\". Input..");
}
} catch(InputMismatchException e) {
System.out.println("Catch blok begin.");
System.out.println("Invalid input, please input a number between 1-4.");
aScanner.nextLine();
selectedMenu = 0;
}
} while(selectedMenu < 1 || selectedMenu > 4);
System.out.println("A new game will now start.");
}
Consider the following alternative (pseudocode):
int getMenuOption() {
print(message)
read(input)
if input is valid then return input
else then return getMenuOption()
}
This is recursive, so if the user sits there and enters bad numbers long enough, you could overflow the stack. You could easily augment this to give the user a fixed number of tries:
int getMenuOption(int triesRemaining) {
if (triesRemaining == 0) throw new RetriesExceededException();
print(message)
read(input)
if input is valid then return input
else then return getMenuOption(triesRemaining - 1)
}
Try something like that (I haven't tested it)
import java.util.Scanner;
import java.util.InputMismatchException;
public class Menu {
public void printMenu() {
System.out.println("1. Start new game\n" + "2. Load game\n"
+ "3. Settings\n" + "4. Exit\n");
}
public void selectMenu() throws InputMismatchException {
int selectedMenu;
boolean validSelection = false;
Scanner aScanner = new Scanner(System.in);
while(!validSelection) {
selectedMenu = aScanner.nextInt();
validSelection = true;
switch (selectedMenu) {
case 1:
// doWhen1();
break;
case 2:
// doWhen2();
break;
case 3:
// doWhen3();
break;
case 4:
// doWhen4();
break;
default:
System.out.println("Input out of range \"" + selectedMenu
+ "\". Input a number between 1-4.");
validSelection = false;
}
}
}
}
Here is a revision to the selectMenu() method you provided that should get the job done! I tested it out and it seems to work as expected. :)
public void selectMenu() {
int selectedMenuItem = 0;
Scanner aScanner = new Scanner(System.in);
while(selectedMenuItem == 0){
String userInputMenuItemString = aScanner.nextLine();
try {
int userInputMenuItem = Integer.parseInt(userInputMenuItemString);
if(userInputMenuItem > 0 && userInputMenuItem <= 4){
selectedMenuItem = userInputMenuItem;
}else{
System.out.println("No option #" + Integer.toString(userInputMenuItem) + " exists!\nTry again:");
}
} catch(NumberFormatException ex) {
System.out.println("Please input a number!");
}
}
switch(selectedMenuItem){
case 1:
System.out.println("You chose to start a new game!");
break;
case 2:
System.out.println("You chose to load a game!");
break;
case 3:
System.out.println("You chose to access settings!");
break;
case 4:
System.out.println("You chose to exit. Bye!");
System.exit(0);
break;
}
}