Java Shut the Box - java

Im writing a program similar to a game called shut the box. The game asks the player to roll 2 die, and then the player chooses to cover both numbers individually (in the boolean array), or the total of the two.
I'm having difficulty returning two values of the int method roll() which is supposed to roll two die.
Heres my code for the main class:
public class clacker {
private int play;
private int die1;
private int die2;
private boolean[] table;
private final int high = 6;
private final int low = 1;
private int range;
public clacker()
{
range = high-low+1;
table = new boolean[13];
play = 0;
}
public void roll()
{
die1 = (int)(Math.random()*range+low);
die2 = (int)(Math.random()*range+low);
}
public void value(char ch)
{
if(ch == 'i' || ch == 'I')
{
table[die1] = true;
table[die2] = true;
displayBoard();
}
else if(ch == 'T' || ch == 't')
{
table[die1+die2] = true;
displayBoard();
}
else
{
roll();
}
}
public void displayBoard()
{
for(int i = 1; i<table.length; i++)
{
if(table[i] == false)
{
System.out.print(" " + i + " ");
}
else
{
System.out.print(" / ");
}
}
}
}
and for the test class:
public class clackerTest {
public static void main(String[] args) {
clacker oo = new clacker();
EasyReader kboard = new EasyReader();
System.out.println("Press anything to roll the dice. ");
char roll= kboard.readChar();
int dice1 = oo.roll();
int dice2 = oo.roll();
System.out.println("You rolled " + dice1 + " and a " + dice2 + "!");
System.out.println("Cover Individual or Total: (enter i or t)");
char roll2 = kboard.readChar();
}
}

Why don't you just roll() twice? Modify roll() to return one int.
public int roll() {
return (int)(Math.random()*range+low);
}
And now, from within clackerTest (java conventions dictates you name this ClackerTest):
int dice1 = oo.roll();
int dice2 = oo.roll();

Related

Making specific moves in a turn based fighting game

I'm trying to make a turn based fighting game in Java Eclipse. Right now there's nothing wrong with my code but I just needed help figuring out a way to add multiple attacks to each of my characters in the game.
This is my main method
public class Main {
public static Random generator = new Random();
public static void main(String[] args) {
String answer = "yes";
while(answer.equals("yes")) {
Character player1 = new Wraith();
Character player2 = new Paladin();
Scanner charInput = new Scanner(System.in);
System.out.println("Player1, Choose your character");
String choice = charInput.nextLine();
if(choice.equals("Paladin")) {
player1 = new Paladin();
}
if(choice.equals("Wizard")) {
player1 = new Wizard();
}
if(choice.equals("Wraith")) {
player1 = new Wraith();
}
System.out.println("Player2, Choose your character");
String choice2 = charInput.nextLine();
if(choice2.equals("Paladin")) {
player2 = new Paladin();
}
if(choice2.equals("Wizard")) {
player2 = new Wizard();
}
if(choice2.equals("Wraith")) {
player2 = new Wraith();
}
//player1.name = input("Player1 pick your character(Paladin, Wraith, Wizard)", charInput);
//player2.name = input("Player2 pick your character(Paladin, Wraith, Wizard)", charInput);
System.out.println(player1.name + " vs. " + player2.name);
System.out.println(player1.health + " vs. " + player2.health);
while (player1.isAlive() && player2.isAlive()) {
System.out.println(player1.name + ": " + player1.health);
System.out.println(player2.name + ": " + player2.health);
int damage;
damage = player1.attack(player2);
System.out.println(player1.name + " hits " + player2.name + " for " + damage);
damage = player2.attack(player1);
System.out.println(player2.name + " hits " + player1.name + " for " + damage);
}
if(player1.isAlive()) {
System.out.println(player1.name + " wins!");
} else if (player2.isAlive()) {
System.out.println(player2.name + " wins!");
} else {
System.out.println("It's a draw!");
}
}
}
private static String input(String string, Scanner charInput) {
return null;
}
}
This is one of my character classes
public class Wizard extends Character {
public int dexterity = 25;
public static Random generator = new Random();
public Wizard(){
super();
this.name = "Wizard";
this.strength = 10;
this.defense = 8;
this.health = 95;
}
public int attack(Character target){
boolean criticalHit =Main.generator.nextInt(150) < dexterity;
int damage = this.strength * 2;
if(criticalHit){
damage *= 2;
System.out.println("*** Critical Hit ***");
}
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
}```
And this is my main character class
public class Character {
public String name;
public int strength;
public int health;
public int defense;
public int takeDamage(int damage){
int damageTaken = damage - this.defense;
this.health -= damageTaken;
return damageTaken;
}
public int attack(Character target){
int damage = this.strength * 2;
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
public boolean isAlive(){
return health > 0;
}
}```
also I'm new to coding and stack overflow so and suggestions on how to make my posts make more sense or something like that is much appreciated
nice implemention of a battle system.
when a Character performs an attack you choose which attack that should be and execute:
public int attack(Character target){
AttackMode mode = determineAttackMode(target); // the charater chooses what kind of attack he will execute during this attack
switch(mode){
case AttackMode.DOUBLESTRIKE: return attackDoubleStrike(target);
case AttackMode.BURST: return attackBurst(target);
default: return attackDefault(target); // your previously implemented method attack(target)
}
}
The AttackMode is an Enum class:
enum AttackMode {DEFAULT, DOUBLESTRIKE, BURST}
i'm not sure how double damage is dealt, so this is a guess here
public int attackDoubleStrike(Character target){
int firstStrike = attackDefault(target);
int secondStrike = attackDefault(target);
return firstStrike + secondStrike;
}

How to return my getWin with more than just true or false

I'm trying to get my program to take multiple different return statements so i can have a win split and lose rather than just win or lose and cant seem to figure out how to do it. My program is made to be able to have either you win and it doubles your bet that you made. If you tie you get your money back. if you lose you lose your bet. Ive gotten win and lose to work previously with using a booelean and returning true or false but needed a way to add in a way to do split.
I've tried multiple methods I've seen online but to no avail any help would be appreciated.
//Import Random Number Generator
import java.util.Random;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
private String Win;
private String Lose;
private String Split;
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
Win = "Win";
}
else if(sum < other.getSum()){
Lose = "Lose";
}
else if(sum == other.getSum()){
Split = "Split";
}
return Win;
}
}//end main
import java.util.Scanner;
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100;
int bet;
int winnings;
int multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
System.out.println(you.getWin());
if(you.getWin()){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else{
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}//end class
I expect to be able to get different return statements that way I can actually set a win aspect a lose aspect but also a split aspect if both players tie.
You have three results to return which are: WIN, LOSE and TIE right?
In that case you have to use three different variables like,
public String Win = "Win",Lose = "Lose",Split = "Split";
and use other variable to store result like result and return this result in getWin(). See below code:
import java.util.Random;
import java.util.Scanner;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
public String Win = "Win",Lose = "Lose",Split = "Split";
private String result = "";
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
result = Win;
}
else if(sum < other.getSum()){
result = Lose;
}
else if(sum == other.getSum()){
result = Split;
}
return result;
}
}//end main
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100,bet,winnings,multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
String result = you.getWin(enemy);
System.out.println(result);
if(result == you.Win){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else if (result == you.Lose){
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}else{
System.out.println("You Split");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}

Poker dice game, and I don't know why my methods have errors on them

public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int[] dice = new int[5];
resetDice(dice);
System.out.print("Your current dice: + dice");
rollDice(dice);
System.out.print(dice);
System.out.println();
promptForReroll(dice, inScanner);
System.out.println("Rerolling...");
rollDice(dice);
System.out.println("Your final dice: + dice");
System.out.println(getResult(dice)+"!");
}
private static void resetDice(int[] dice) {
int length = 5;
for(int i = 0; i < length; i++){
dice[i] = 0;
}
}
private static void rollDice(int[] dice) {
int i = 0;
int length = 5;
while(i < length) {
if(dice[i] == 0) {
int roll = (int)(Math.random()*6)+1;
dice[i] = roll;
i++;
}
}
}
private static String diceToString(int[] dice) {
String diceToString =("Your current dice: " +dice[0]+", " +dice[1]+ ", " +dice[2]+ ", " +dice[3]+ ", " +dice[4]);
return diceToString;
}
private static void promptForReroll(int[] dice, Scanner inScanner) {
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
int selection = inScanner.nextInt();
while(selection != -1){
if(selection > 4 || selection < -1){
System.out.println("Erorr: Index must be between 0 and 4 (-1 to quit)!");
}
else{
dice[selection] = 0;
}
System.out.println("Your current dice: " + dice);
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
selection = inScanner.nextInt();
}
System.out.println("Keeping remaining die...");
}
private static boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
}
private static String getResult(int[] dice) {
getCounts(dice);
}
private static int[] getCounts(int[] dice) {
int[] count = new int[6];
int i = 0;
int j = 0;
while(i<5){
while(j<5){
if(dice[i] == (j+1)){
count[j]++;
i++;
}
else{
i++;
}
j++;
}
}
return count;
}
I have written out the coding, and I think for the most part it may be right, but I can't run it because it has errors on my promptForPlayAgain method, and my getResult method. I don't know why there are errors on them.
You aren't returning anything if the user's input isn't "Y" or "N". You need to add an else case:
private static Boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
else
{
//Do something here to handle bad input.
}
}
Ideally though, you should be doing some kind of formatting and preverification of the input, like forcing the input to upper case before comparing.
And on getResult, you aren't returning anything. Add a return before the body of the function. That won't fix it though, since the return type of getValue doesn't match getResult. You're trying to return a int array as a string.
In the future, please include the actual error messages they you receive.

Why wont my Strings compare?

Ok, so I was assigned to make a Dice program that could be called to roll a dice and return the side it landed on. I got the Dice part of it done. However when I run my program, my if statement doesn't execute to increment Counter if both die equal 6. What is wrong with my program.
This is the main:
public class PairOfDice {
public static void main(String[] args) {
int Counter = 0;
Dice D1 = new Dice();
Dice D2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
D1.Roll();
D2.Roll();
if (D1.equals(6) && D2.equals(6))
{
Counter++;
}
else
{
System.out.print ("Dice 1 = " + D1 + " | ");
System.out.println ("Dice 2 = " + D2);
}
}
System.out.print ("There were " + Counter + " Box Cars");
}
}
And this is my Dice function:
public class Dice {
private int Side;
public Dice()
{
Roll();
}
public void Roll()
{
Side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(Side);
return A;
}
}
You seem to have missed what .Equals() means:
D1.equals(6)
D1 doesn't equal 6. D1 is an instance of a Dice object, and 6 is an integer. You need to determine if the integer value within D1 equals 6.
First, create a getter for that value on the Dice class:
public int getSide()
{
return Side;
}
Then use that in the comparisons:
if (D1.getSide() == 6 && D2.getSide() == 6)
You need to check if the value of the die equals the value 6. Right now you are comparing the value of dice object to a number which doesn't make sense. Override equals or provide a getter for the value of the die.
I figured it out All I did was change if (D1.equals(6) && D2.equals(6)) to if (D1.equals(6) && D2.equals(6)) and removed the else part of the if statement, and put the print out before the if statement.
This is the main:
public class PairOfDice {
public static void main(String[] args) {
int Counter = 0;
Dice D1 = new Dice();
Dice D2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
D1.Roll();
D2.Roll();
System.out.print ("Dice 1 = " + D1 + " | ");
System.out.println ("Dice 2 = " + D2);
if (D1.Side == 6 && D2.Side == 6)
{
Counter++;
}
}
System.out.print ("There were " + Counter + " Box Cars");
}
}
This is Dice:
public class Dice {
int Side;
public Dice()
{
Roll();
}
public void Roll()
{
Side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(Side);
return A;
}
}
Please try below logic
public class PairOfDice {
public static void main(String[] args) {
int counter = 0;
Dice d1 = new Dice();
Dice d2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
d1.roll();
d2.roll();
if (d1.getSide()==6 && d2.getSide()==6)
{
counter++;
}
else
{
System.out.print ("Dice 1 = " + d1 + " | ");
System.out.println ("Dice 2 = " + d2);
}
}
System.out.print ("There were " + counter + " Box Cars");
}
}
public class Dice {
private int side;
public Dice()
{
roll();
}
public void roll()
{
side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(side);
return A;
}
public int getSide() {
return side;
}
}

Array not printing properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}

Categories

Resources