I'm having an issue with my game - java

So I'm making a basic game, and I'm having an issue it's that battle two won't start, battle one is working really well, but for some reason battle two won't start...
Heres the code:
import java.util.Scanner;
public class Game {
public int Health = 10;
public int Enemy_Health = 25;
public int Your_Health = 20;
public int Battle = 1;
public int Move = 0;
public void Method() {
System.out.println("A random battle started!" + "\n");
System.out.println("It's health is currently at " + Health + "\n");
System.out.println("Your health is currently at " + Your_Health + "\n");
System.out.println("Would you like to use bite or slash?" + "\n");
//-----Battle 1-----\\
while (Battle == 1) {
if (Battle == 1) {
Scanner Scan = new Scanner(System.in);
String a = Scan.nextLine();
if (a.equals("bite")) {
System.out.println("You used bite!" + "\n");
System.out.println("You did 5 damage!" + "\n");
Health -= 5;
Move++;
System.out.println("It's health is now at " + Health + "\n");
} else if (a.equals("slash")) {
System.out.println("You used slash!" + "\n");
System.out.println("You did 2 Damage!" + "\n");
Health -= 2;
System.out.println("It's health is now at " + Health + "\n");
System.out.println("You did 3 Damage!" + "\n");
Health -= 3;
Move ++;
System.out.println("It's health is now at " + Health + "\n");
}
if (Move == 1) {
System.out.println("---------------------------" + "\n");
System.out.println("It used Bite" + "\n");
System.out.println("It did 5 damage!" + "\n");
Your_Health -= 5;
System.out.println("Your health is now at " + Your_Health + "\n");
System.out.println("---------------------------" + "\n");
System.out.println("Would you like to use bite or slash?" + "\n");
}
if (Health == 0) {
System.out.println("You won!" + "\n");
System.out.println("You gained 100$!" + "\n" + "You now have 150$!");
System.out.println("You gained 100 Xp!" + "\n" + "You leveled up!" + "\n" + "50 Xp left tell Level 2" + "\n" + "New move learned: " + "\n" +
"Knock Out!" + "\n" + "Your health went up by 5!" + "\n");
System.out.println("Swirl will make the enemy dizzy for one round!" + "\n" + "\n");
Your_Health += 5;
Battle -= 0;
Move = 0;
Health = -1;
}
while (Battle == 0){
Battle = 2;
}
//-----Battle 2-----\\
while (Battle == 2) {
if (Enemy_Health == 25) {
System.out.println("A random battle has started!" + "\n");
System.out.println("It's health is currently at " + Enemy_Health + "\n");
System.out.println("Your health is currently at " + Your_Health + "\n");
System.out.println("Would you like to use bite, slash or swirl?" + "\n");
if (a.equals("bite")) {
System.out.println("You used bite!" + "\n");
System.out.println("You did 5 damage!" + "\n");
Health -= 5;
System.out.println("It's health is now at " + Health + "\n");
} else if (a.equals("slash")) {
System.out.println("You used slash!" + "\n");
System.out.println("You did 2 Damage!" + "\n");
Health -= 2;
Move++;
System.out.println("It's health is now at " + Health + "\n");
System.out.println("You did 3 Damage!" + "\n");
Health -= 3;
Move++;
System.out.println("It's health is now at " + Health + "\n");
} else if (a.equals("swirl")) {
System.out.println("You used Swirl" + "\n");
System.out.println("It got dizzy for one round." + "\n");
}
if (Move == 1) {
System.out.println("---------------------------" + "\n");
System.out.println("It used Slash" + "\n" + "It did 2 damage!" + "\n" + "It did 3 damage!" + "\n");
Your_Health -= 5;
System.out.println("Your health is now at " + Your_Health + "\n");
System.out.println("---------------------------" + "\n");
System.out.println("Would you like to use bite or slash?" + "\n");
}
if (Move == 2){
System.out.println("---------------------------" + "\n");
System.out.println("It used Bite" + "\n" + "It did 5 damage!" + "\n");
Your_Health -= 5;
System.out.println("Your health is now at " + Your_Health + "\n");
System.out.println("---------------------------" + "\n");
System.out.println("Would you like to use bite or slash?" + "\n");
}
if (Move == 3){
System.out.println("---------------------------" + "\n");
System.out.println("It used Head Butt" + "\n" + "It did 10 damage!" + "\n" + "It took 5 damage" + "\n");
Your_Health -= 10;
Enemy_Health -= 5;
System.out.println("Your health is now at " + Your_Health + "\n");
System.out.println("---------------------------" + "\n");
System.out.println("Would you like to use bite or slash?" + "\n");
}
}
}
}
}
}
}

After the first run through your while loop Health will be < 10, so your if block is not run anymore. Since I don't see any benefit from it, I'd suggest you just remove the if(Health==10) block.
Also as mentioned in the comments: Health and battle should be int not float.
After fixing the other issues you will notice that the battle never ends and you can never win by bite: Your check for the win condition has to be outside of the other ifs and set Battle to something != 1
In total your game should probably looks something like this:
public class Game {
public int Health = 10;
public int Battle = 1;
public void Method() {
System.out.println("A random battle started!" + "\n");
System.out.println("It's health is currently at " + Health + "\n");
System.out.println("Would you like to use bite or slash?" + "\n");
while (Battle == 1) {
Scanner Scan = new Scanner(System.in);
String a = Scan.nextLine();
if (a.equals("bite")) {
System.out.println("You used bite!"+ "\n");
System.out.println("You did 5 damage!"+ "\n");
Health -= 5;
System.out.println("It's health is now at " + Health + "\n");
System.out.println("Would you like to use bite or slash?"+ "\n");
} else if (a.equals("slash")) {
System.out.println("You used slash!"+ "\n");
System.out.println("You did 2 Damage!"+ "\n");
Health -= 2;
System.out.println("It's health is now at " + Health+ "\n");
System.out.println("You did 2 Damage!"+ "\n");
Health -= 2;
System.out.println("It's health is now at " + Health+ "\n");
System.out.println("Would you like to use bite or slash?"+ "\n");
}
if (Health <= 0) {
System.out.println("You won!"+ "\n");
System.out.println("You gained 100$!" + "\n" + "You now have 150$!");
Battle = 0;
}
}
}
}
}

Related

How to make a loop not ask for input after the last run?

I am doing a project that requires me to run a loop that requires user input after every run and stops after a certain number of times. I have it working but have a weird quirk that I cannot figure out... How to make it stop asking for input after the last run. Any help would be appreciated. Thanks!
public class TestCard {
/**
* #param args
*/
public static void main(String[] args) {
int i = 0,
player = 0,
dealer = 0,
tie = 0;
Scanner input = new Scanner(System.in);
String answer = "";
do {
Card card1 = new Card();
Card card2 = new Card();
if (card1.getValue() > card2.getValue()) {
System.out.println("Your card: " + card1);
System.out.println("Dealer card: " + card2);
i++;
player++; // adds to player win total.
System.out.println("You win!");
System.out.println("Total score - Player: " + player + ", Dealer: " + dealer + ", Ties: " + tie);
} else if (card1.getValue() < card2.getValue()) {
System.out.println("Your card: " + card1);
System.out.println("Dealer card: " + card2);
i++;
dealer++;
System.out.println("Dealer wins!");
System.out.println("Total score - Player: " + player + ", Dealer: " + dealer + ", Ties: " + tie);
} else {
System.out.println("Your card: " + card1);
System.out.println("Dealer card: " + card2);
i++;
tie++;
System.out.println("Tie!");
System.out.println("Total score - Player: " + player + ", Dealer: " + dealer + ", Ties: " + tie);
}
System.out.println("Play again? Y/N (Draws left: " + (26 - i) + ")");
answer = input.next();
answer = answer.toLowerCase();
if (answer.equals("y")) {
card1.getValue();
card2.getValue();
} else if (answer.equals("n")) {
System.out.println("Thanks for playing!");
} else {
while (!answer.equals("y") && !answer.equals("n")) {
System.out.println("Please input Y or N");
answer = input.next();
answer = answer.toLowerCase();
}
}
}
while (answer.equals("y") && (i < 26));
System.out.println("Game over! Totals - Player: " + player + ", Dealer: " + dealer + ", Ties: " + tie + ", Total draws: " + i);
input.close();
}
}

Output keeps repeating and does not loop nor does it end the program after entering Y or N - Java

I have an issue with it looping the same output even though I have entered the correct input to end the loop. This is the output that kept repeating Invalid input. Please enter again! Would you like to enter another student's mark? [Y/N]. I have looked at the code for possible error but I couldn't figure out where had the code gone wrong for an error to occur. Below is the full code.
import java.util.Scanner;
public class tutorial {
#SuppressWarnings("empty-statement")
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String id, inpTutorial, inpAssignment, inpTest, inpProject, inpFinalExam, reenter = "", enter = "", reenterAgain = "", enterAgain = "";
int A = 80, B = 65, C = 50, D = 40, F = 0, bPlus = B + 5, cPlus = C + 5;
Double tutorial = 0.0, assignment = 0.0, test = 0.0, project = 0.0, finalExam = 0.0, tutorialMarks = 0.0, assignmentMarks =0.0, testMarks = 0.0, projectMarks = 0.0, finalExamMarks = 0.0;
double totalMarks = 0.0;
do {
do {
System.out.println("Please enter ID");
id = input.next();
if(id.isEmpty()) {
System.out.println("ID should not be empty!\n");
}
else {
do {
System.out.println("Please enter tutorial marks");
inpTutorial = input.next();
tutorial = Double.parseDouble(inpTutorial);
if (tutorial < 0) {
System.out.println("Tutorial marks cannot be a negative!\n");
}
else if (tutorial > 100) {
System.out.println("Tutorial marks can only be 100%\n");
}
else if (tutorial == null) {
System.out.println("Tutorial marks must have a value!");
}
else {
do {
System.out.println("Please enter assignment marks");
inpAssignment = input.next();
assignment = Double.parseDouble(inpAssignment);
if (assignment < 0) {
System.out.println("Assignment marks cannot be a negative!\n");
}
else if (assignment > 100) {
System.out.println("Assignment marks can only be 100%\n");
}
else if (assignment == null) {
System.out.println("Assignment marks must have a value!");
}
else {
do {
System.out.println("Please enter test marks");
inpTest = input.next();
test = Double.parseDouble(inpTest);
if (test < 0) {
System.out.println("Test marks cannot be a negative!\n");
}
else if (test > 100) {
System.out.println("Test marks can only be 100%\n");
}
else if (test == null) {
System.out.println("Test marks must have a value!");
}
else {
do {
System.out.println("Please enter project marks");
inpProject = input.next();
project = Double.parseDouble(inpProject);
if (project < 0) {
System.out.println("Project marks cannot be a negative!\n");
}
else if (project > 100) {
System.out.println("Project marks can only be 100%\n");
}
else if (project == null) {
System.out.println("Project marks must have a value!");
}
else {
do {
System.out.println("Please enter final examination marks");
inpFinalExam = input.next();
finalExam = Double.parseDouble(inpFinalExam);
if (finalExam < 0) {
System.out.println("Final examination marks cannot be a negative!\n");
}
else if (finalExam > 100) {
System.out.println("Final examination marks can only be 100%\n");
}
else if (finalExam == null) {
System.out.println("Final examination marks must have a value!");
}
else {
tutorialMarks = (tutorial/100)*10;
assignmentMarks = (assignment/100)*10;
testMarks = (test/100)*20;
projectMarks = (project/100)*20;
finalExamMarks = (finalExam/100)*40;
totalMarks = tutorialMarks + assignmentMarks + testMarks + projectMarks + finalExamMarks;
System.out.println("Your ID is: " + id);
int marksTotal= (int) Math.round(totalMarks);
System.out.printf("Your total marks is %d%%\n", marksTotal);
if(marksTotal < 100 && marksTotal >= 80) {
System.out.println("Your grade is A");
}
else if (marksTotal >= 70) {
System.out.println("Your grade is B+");
}
else if (marksTotal >= 65) {
System.out.println("Your grade is B");
}
else if (marksTotal >= 55) {
System.out.println("Your grade is C+");
}
else if (marksTotal >= 50) {
System.out.println("Your grade is C");
}
else if (marksTotal >= 40) {
System.out.println("Your grade is D");
}
else if (marksTotal >= 0) {
System.out.println("Your grade is F");
}
else {
System.out.println("Invalid grade!");
}
if (marksTotal > 77) {
int gradeA = A - marksTotal;
if (gradeA == 1){
System.out.printf("Total marks: %.1f. After round up is %d. %d-%d is %d mark. Borderline\n",totalMarks,marksTotal,A,marksTotal,gradeA);
}
else if (gradeA != 1 && gradeA != 0){
System.out.printf("Total marks: %.1f. After round up is %d. %d-%d is %d mark. Not borderline\n",totalMarks,marksTotal,A,marksTotal,gradeA);
}
else {
System.out.printf("Total marks: %.1f. After round up is %d. %d-%d is %d mark.\n",totalMarks,marksTotal,A,marksTotal,gradeA);
}
}
else if (marksTotal > 67) {
int gradeBPlus = bPlus - marksTotal;
if (gradeBPlus == 1){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + bPlus + "-" + marksTotal + " is " + gradeBPlus + " mark. Borderline");
}
else if (gradeBPlus != 1 && gradeBPlus != 0){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + bPlus + "-" + marksTotal + " is " + gradeBPlus + " mark. Not borderline");
}
else {
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + bPlus + "-" + marksTotal + " is " + gradeBPlus + " mark.");
}
}
else if (marksTotal > 62) {
int gradeB = B - marksTotal;
if (gradeB == 1){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + B + "-" + marksTotal + " is " + gradeB + " mark. Borderline");
}
else if (gradeB != 1 && gradeB != 0){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + B + "-" + marksTotal + " is " + gradeB + " mark. Not borderline");
}
else {
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + B + "-" + marksTotal + " is " + gradeB + " mark.");
}
}
else if (marksTotal > 52) {
int gradeCPlus = cPlus - marksTotal;
if (gradeCPlus == 1){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + cPlus + "-" + marksTotal + " is " + gradeCPlus + " mark. Borderline");
}
else if (gradeCPlus != 1 && gradeCPlus != 0){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + cPlus + "-" + marksTotal + " is " + gradeCPlus + " mark. Not borderline");
}
else {
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + cPlus + "-" + marksTotal + " is " + gradeCPlus + " mark.");
}
}
else if (marksTotal > 47) {
int gradeC = C - marksTotal;
if (gradeC == 1){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + C + "-" + marksTotal + " is " + gradeC + " mark. Borderline");
}
else if (gradeC != 1 && gradeC != 0){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + C + "-" + marksTotal + " is " + gradeC + " mark. Not borderline");
}
else {
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + C + "-" + marksTotal + " is " + gradeC + " mark.");
}
}
else if (marksTotal > 37) {
int gradeD = D - marksTotal;
if (gradeD == 1){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + D + "-" + marksTotal + " is " + gradeD + " mark. Borderline");
}
else if (gradeD != 1 && gradeD != 0){
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + D + "-" + marksTotal + " is " + gradeD + " mark. Not borderline");
}
else {
System.out.println("Total marks: " + totalMarks + ". After round up is " + marksTotal + ". " + D + "-" + marksTotal + " is " + gradeD + " mark.");
}
}
else {
System.out.print("Invalid total marks!");
}
}
}while(finalExam > 100 || finalExam < 0);
}
}while(project > 100 || project < 0);
}
}while(test > 100 || test < 0);
}
}while(assignment > 100 || assignment < 0);
}
}while(tutorial > 100 || tutorial < 0);
}
}while(id.isEmpty());
System.out.println("Would you like to enter another student's mark? [Y/N]");
reenter = input.next();
enter = reenter.toLowerCase();
while(!"Y".equals(enter) || !"N".equals(enter)) {
System.out.println("Invalid input. Please enter again!\nWould you like to enter another student's mark? [Y/N]");
reenterAgain = input.next();
enterAgain = reenterAgain.toLowerCase();
}
}while(enterAgain.equalsIgnoreCase("Y"));
}//end main
}//end class
Here is the particular part that I am having a problem with.
System.out.println("Would you like to enter another student's mark? [Y/N]");
reenter = input.next();
enter = reenter.toLowerCase();
while(!"Y".equals(enter) || !"N".equals(enter)) {
System.out.println("Invalid input. Please enter again!\nWould you like to enter another student's mark? [Y/N]");
reenterAgain = input.next();
enterAgain = reenterAgain.toLowerCase();
}

Certain "if" statements containing print lines not being executed and thus not printing onto the console

I am coding a text-based java game where the user types in certain inputs to ultimately defeat an enemy. I want to create a score by writing out if statements that state if the damage done on the enemy was x amount, then award x points. However, I believe the if statement is being skipped over because it is not printing the print statements.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
game gameObject = new game();
gameObject.runGame();
}
}
class game {
public void runGame() {
// System Objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game Variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assasain"};
int maxEnemyHealth = 100;
int enemyAttackDamage = 50;
// Player Variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
int counter = 0;
int points =0;
boolean running = true;
System.out.println("Welcome to the Dungeon!");
GAME:
while (running) {
System.out.println("-----------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + " has appeared! #\n");
while (enemyHealth > 0) {
System.out.println("\tYour HP: " + health);
System.out.println("\t" + enemy + "'s HP: " + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink health potion");
System.out.println("\t3. Run!");
String input = in.nextLine();
if (input.equals("1")) {
int damageDealt = rand.nextInt(attackDamage);
int damageTaken = rand.nextInt(enemyAttackDamage);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t> You strike the " + enemy + " for " + damageDealt);
System.out.println("\t> You recieve " + damageTaken + " in retaliation!");
if (health < 1) {
System.out.println("\t> You have taken too much damage, you are too weak to move on!");
break;
}
if (damageDealt > 20) {
points += 50;
System.out.print("You gained 50 points. You have" + points + " points in total.");
}
else if (damageDealt > 30) {
points += 60;
System.out.print("You gained 60 points. You have" + points + " points in total.");
}
else if (damageDealt >50) {
points += 100;
System.out.print("You gained 100 points. You have" + points + " points in total.");
}
}
else if (input.equals("2")) {
if (numHealthPotions > 0) {
health += healthPotionHealAmount;
numHealthPotions--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP."
+ "\n\t> You have " + numHealthPotions + " health potionsleft.\n");
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies to get a chance to get one.\n");
}
}
else if (input.equals("3")) {
System.out.println("\tYou run away from the " + enemy + "!");
continue GAME;
}
else {
System.out.println("\tInvalid command.");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle!");
break;
}
System.out.println("-----------------------------------");
System.out.println(" # " + enemy + " was defeated! #");
System.out.println(" # You have " + health + " HP left. #");
if (rand.nextInt(100) < healthPotionDropChance) {
numHealthPotions++;
System.out.println(" # The " + enemy + " dropped a health potion! # ");
System.out.println(" # You now have " + numHealthPotions + " health potion(s). #");
}
System.out.println("-----------------------------------");
System.out.println("What would you like to do now?");
System.out.println("1. Continue fighting");
System.out.println("1. Exit the dungeon");
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.print("Invalid command!");
input = in.nextLine();
}
if (input.contentEquals("1")) {
System.out.println("You continue on your adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventures!");
break;
}
counter++;
}
}
class exit {
public String byeStatements () {
String format;
String thanks;
format = "###########";
thanks = "Thanks for playing!";
System.out.println(format);
System.out.println(thanks);
return (format + thanks);
}
}

Static variables are getting initialized again when ever function gets called - Java

I want to have the userScore and computerScore updated every time the user inputs 'y' to play again, but instead, the scores get initialized from 0.
I have made an ArrayList to show the results every time user plays. Does Anyone have any suggestion on a better implementation for this?
Please ignore violation of the DRY principal :)
import java.util.*;
import java.io.*;
class OddsAndEvens{
static int UserScore = 0;
static int computerScore = 0;
static ArrayList<Integer> UserScoreArray = new ArrayList<Integer>();
static ArrayList<Integer> computerScoreArray = new ArrayList<Integer>();
public static void main(String args[]){
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String name = "", choice="";
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("Let's play a game called Odds and Evens");
System.out.print("What is your name? ");
try{
name = console.readLine();
} catch(Exception e){
System.out.println("Error while name input: " + e);
}
System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");
try{
choice = console.readLine().toLowerCase();
} catch(Exception e){
System.out.println("Error while Choosing Odd or Even: " + e);
}
if(choice.startsWith("o")){
System.out.println(name + " chose ODDS, the Computer will be EVENS");
} else if(choice.startsWith("e")){
System.out.println(name + " chose EVENS, the Computer will be ODDS");
} else{
System.out.println("Enter a valid choice "+ name + "..Either O(o) or E(e)");
}
System.out.println("______________________________________________________________________________");
System.out.println();
while(play(console, name, choice, UserScore, computerScore).startsWith("y")){
play(console, name, choice, UserScore, computerScore);
}
}
public static String play(BufferedReader console, String name, String choice, int UserScore, int computerScore){
int numberOfFingers = 0;
UserScoreArray.add(0);
computerScoreArray.add(0);
System.out.println("How many 'fingers' do you put out?(You can only put out 5 fingers)");
try{
numberOfFingers = Integer.parseInt(console.readLine());
} catch(Exception e1){
System.out.println("Error while, taking number of fingers: " + e1);
}
if(numberOfFingers > 5){
System.out.println("You cannot put out more than 5 fingers " + name);
System.out.println("Let's try again!");
play(console, name, choice, UserScore, computerScore);
}
Random rand = new Random();
int computerFingers = rand.nextInt(6);
System.out.println("The computer played: " + computerFingers);
int sum = numberOfFingers + computerFingers;
System.out.println("sum = " + numberOfFingers + "+" + computerFingers);
if(sum%2 == 0){
System.out.println(sum + " is. . . . Even");
if(choice.startsWith("e")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
} else{
System.out.println(sum + " is. . . . Odd");
if(choice.startsWith("o")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
}
System.out.println("______________________________________________________________________________");
System.out.println(name + "'s Array List contents: " + "\n" + UserScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println("Computer's Array List contents: " + "\n" + computerScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("How does the Score look like " + name + ", Want to Play again?(y or n)");
String playAgain = "";
try{
playAgain = console.readLine().toLowerCase();
} catch(Exception e3){
System.out.println("Error in function for playAgain: " + e3);
}
if(playAgain.startsWith("y")){
System.out.println("Starting another game-");
return playAgain;
}
else{
System.out.println("Thank you for playing, see you soon..");
System.exit(0);
}
return "p";
}
}
Please note that static variable is seen in all instances of a class. You don't need to pass it as a parameter to a method.
If you pass it as a parameter, please note the parameter name. If your variable is called "score" and your parameter is called "score" as well, what you are changing (with "score++" or other "score" manipulation) is no longer the "score" class variable, but a method parameter, and changes done to it will no longer be visible when you exit the method. This is called shadowing.
I suggest (for similar questions) a sister-site to SO - one that deals with code reviews. https://codereview.stackexchange.com/ You may learn more there, since here we tend to focus on specific problems.
Try this code , it will works, you need to intialies index 0 of 2 arrays in the beginining of main method
Here is the code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
class OddsAndEvens{
static int UserScore = 0;
static int computerScore = 0;
static ArrayList<Integer> UserScoreArray = new ArrayList<Integer>();
static ArrayList<Integer> computerScoreArray = new ArrayList<Integer>();
public static void main(String args[]){
UserScoreArray.add(0);
computerScoreArray.add(0);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String name = "", choice="";
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("Let's play a game called Odds and Evens");
System.out.print("What is your name? ");
try{
name = console.readLine();
} catch(Exception e){
System.out.println("Error while name input: " + e);
}
System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");
try{
choice = console.readLine().toLowerCase();
} catch(Exception e){
System.out.println("Error while Choosing Odd or Even: " + e);
}
if(choice.startsWith("o")){
System.out.println(name + " chose ODDS, the Computer will be EVENS");
} else if(choice.startsWith("e")){
System.out.println(name + " chose EVENS, the Computer will be ODDS");
} else{
System.out.println("Enter a valid choice "+ name + "..Either O(o) or E(e)");
}
System.out.println("______________________________________________________________________________");
System.out.println();
while(play(console, name, choice, UserScore, computerScore).startsWith("y")){
play(console, name, choice, UserScore, computerScore);
}
}
public static String play(BufferedReader console, String name, String choice, int UserScore, int computerScore){
int numberOfFingers = 0;
System.out.println("How many 'fingers' do you put out?(You can only put out 5 fingers)");
try{
numberOfFingers = Integer.parseInt(console.readLine());
} catch(Exception e1){
System.out.println("Error while, taking number of fingers: " + e1);
}
if(numberOfFingers > 5){
System.out.println("You cannot put out more than 5 fingers " + name);
System.out.println("Let's try again!");
play(console, name, choice, UserScore, computerScore);
}
Random rand = new Random();
int computerFingers = rand.nextInt(6);
System.out.println("The computer played: " + computerFingers);
int sum = numberOfFingers + computerFingers;
System.out.println("sum = " + numberOfFingers + "+" + computerFingers);
if(sum%2 == 0){
System.out.println(sum + " is. . . . Even");
if(choice.startsWith("e")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore + computerScoreArray.get(computerScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
} else{
System.out.println(sum + " is. . . . Odd");
if(choice.startsWith("o")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore + computerScoreArray.get(computerScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
}
System.out.println("______________________________________________________________________________");
System.out.println(name + "'s Array List contents: " + "\n" + UserScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println("Computer's Array List contents: " + "\n" + computerScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("How does the Score look like " + name + ", Want to Play again?(y or n)");
String playAgain = "";
try{
playAgain = console.readLine().toLowerCase();
} catch(Exception e3){
System.out.println("Error in function for playAgain: " + e3);
}
if(playAgain.startsWith("y")){
System.out.println("Starting another game-");
return playAgain;
}
else{
System.out.println("Thank you for playing, see you soon..");
System.exit(0);
}
return "p";
}
}
This happens because of your method parameters.You have two unwanted
method parameters in your play method.just remove UserScore &
computerScore parameters from your play method and your code should work well.
In your class, UserScore & computerScore fields are static. so no
need to pass those field values to another static method within the
same class.In your code those parameters just hide the actual static
fields.when you print the value of UserScore or computerScore in play
method, java just print the value of the local method parameters
instead of static fields.

Why doesn't this method / array pass return 1 for frequency

For this I wanted to print out the frequencies of the amount of times each types of car was chosen... however, as I run the program, its printing out a 0 (for frequency) each time I chose honda for example.
It would be better to print out a table of all frequencies at the end of each program, however I'm just not sure how to get there.
public static void main(String[] args) {
int prompt;
int[] carsValues = new int[5];//didnt want to use 0
do{
prompt = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter"
+ "\n"
+ "1 For Honda"
+ "\n"
+ "2 For Toyota"
+ "\n"
+ "3 For Ford"
+ "\n"
+ "4 For Chevrolet"
+ "\n"
+ "5 For Kia"
+ "\n"
+ "6 To Quit"));
if (prompt == 1)
{
display(carsValues);
int n = 1;
carsValues[n]++;
display(carsValues);
};
if (prompt == 2)
{
display(carsValues);
int n = 2;
carsValues[n]++;
display(carsValues);
};
if (prompt == 3)
{
display(carsValues);
int n = 3;
carsValues[n]++;
display(carsValues);
};
if (prompt == 4)
{
display(carsValues);
int n = 4;
carsValues[n]++;
display(carsValues);
};
if (prompt ==5)
{
display(carsValues);
int n = 5;
carsValues[n]++;
display(carsValues);
}
if (prompt >= 7)
{
JOptionPane.showMessageDialog(null, "Unrecognizable Command"
+ "\n"
+ "Error: Entered Option Is Greater Than The Choice of 5"
+ "\n"
+ "Try Again"
+ "\n");
};
if (prompt <= 0)//child proofing
{
JOptionPane.showMessageDialog(null, "Unrecognizable Command"
+ "\n"
+ "Error: Entered Option Is A 0 Or A Negative"
+ "\n"
+ "Try Again"
+ "\n");
};
}while(prompt!= 6);
}
public static void display(int[] input){
try{
int miles, gallons, mpg;
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
if (miles <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
}
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
if (gallons <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
}
mpg = miles/gallons;
JOptionPane.showMessageDialog(null, String.format("MPG Turns Out To Be %n" + mpg));
}catch(ArithmeticException mathError){
JOptionPane.showMessageDialog(null, "Division by Zero"
+ "\n"
+ "Can't Do That");
}
for(int counter = 0; counter < input.length; counter++){
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"+(input[counter]));
break;// bad idea
}
}
}
because carsValues[0] is never increased and yet you print only carsValues[0] every time. look at the break in the for loop:
for(int counter = 0; counter < input.length; counter++){
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"+(input[counter]));
break;// bad idea
}
In your example, the last loop:
for(int counter = 0; counter < input.length; counter++){
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"+(input[counter]));
break;// bad idea
The loop breaks after 0 everytime, and carsValues[0] is never used. So your result will always be 0.
Here's a way that would work. It can be refactored depending on your skill level.
import javax.swing.JOptionPane;
public class HelloWorld
{
public static void main(String[] args) {
int prompt;
int[] carsValues = new int[6];//didnt want to use 0
do{
prompt = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter"
+ "\n"
+ "1 For Honda"
+ "\n"
+ "2 For Toyota"
+ "\n"
+ "3 For Ford"
+ "\n"
+ "4 For Chevrolet"
+ "\n"
+ "5 For Kia"
+ "\n"
+ "6 To Quit"));
if(prompt < 0 || prompt > 6){
JOptionPane.showMessageDialog(null, "Unrecognizable Command"
+ "\n"
+ "Error: Entered Option must be between 1 and 5 inclusive"
+ "\n"
+ "Try Again"
+ "\n");
}
else{
int n = prompt;
carsValues[n]++;
display(carsValues);
}
}while(prompt!= 6);
}
public static void display(int[] input){
try{
int miles, gallons, mpg;
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
if (miles <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
}
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
if (gallons <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
}
mpg = miles/gallons;
JOptionPane.showMessageDialog(null, String.format("MPG Turns Out To Be %n" + mpg));
}catch(ArithmeticException mathError){
JOptionPane.showMessageDialog(null, "Division by Zero"
+ "\n"
+ "Can't Do That");
}
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"
+ "Honda: " + input[1]
+ "\n"
+ "Toyota: " + input[2]
+ "\n"
+ "Ford: " + input[3]
+ "\n"
+ "Chevrolet: " + input[4]
+ "\n"
+ "Kia: " + input[5]
+ "\n");
}
}

Categories

Resources