Static variables are getting initialized again when ever function gets called - Java - 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.

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();
}
}

How can I print something based on the result of a boolean method?

I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.

Program crashes even with try and catch statements

one problem I noticed is that the program crashes if you enter non digits even though there is a catch statement. can someone help me out? I can't seem to find the problem.
Can you also explain what I'm doing wrong and why it's wrong? Thank you in advance.
//previous code had an issue while I was creating a new scanner. it's correct now.
import java.util.*;
public class HighLow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numberOfAttempts = 0;
System.out.println("WIN THE THREE ROUNDS TO WIN THE GAME!.");
int theNumber = (int) (Math.random() * 10 + 1);
System.out.println("Round 1: I am thinking of a number between" + "\n" + "1 and 10, can you guess the number in " + "\n" + "less than 3 attempts?");
System.out.println("Type a number below and press enter.");
int guess = 0;
do {
try {
guess = scan.nextInt();
if (guess != theNumber) {
if (guess < theNumber) {
System.out.println("Sorry " + guess + " is too low, please try again");
}else if (guess > theNumber) {
System.out.println("Sorry " + guess + " is too high, please try again." );
}
numberOfAttempts = numberOfAttempts + 1;
}else {
System.out.println(guess + " is the correct answer. You got it on" + "\n" + "attempt number " + (numberOfAttempts + 1) + ". Proceeding to round 2.");
theNumber = (int) (Math.random() * 100 + 1);
System.out.println("\n" + "Round 2: I am thinking of a number between " + "\n" + "1 and 100, can you guess the number in " + "\n" + "less than 6 attempts?");
numberOfAttempts = 0;
int secondRoundGuess = 0;
do {
try {
secondRoundGuess = scan.nextInt();
if (secondRoundGuess != theNumber) {
if (secondRoundGuess < theNumber) {
System.out.println("Sorry " + secondRoundGuess + " is too low, please try again");
}else{
System.out.println("Sorry " + secondRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}
else {
System.out.println(secondRoundGuess + " is the correct answer. You got it on " + "\n" + "attempt number " + (numberOfAttempts + 1) + "." + "\n" + "Proceeding to round 3.");
System.out.println("\n" + "Round 3: I am thinking of a number between " + "\n" + "1 and 1000, can you guess the number in " + "\n" + "less than 10 attempts?");
theNumber = (int)(Math.random() * 1000 + 1);
numberOfAttempts = 0;
int thirdRoundGuess = 0;
do {
try {
thirdRoundGuess = scan.nextInt();
if (thirdRoundGuess != theNumber) {
if (thirdRoundGuess < theNumber) {
System.out.println("Sorry " + thirdRoundGuess + " is too low, please try again");
}else {
System.out.println("Sorry " + thirdRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}else{
System.out.println(thirdRoundGuess + " is the correct answer.");
System.out.println("You won the game, you are a badass." + "\n" + "I made this game and I cant even beat " + "\n" + "level 3.");
System.out.println("I am a newbie at programming and it's my " + "\n" + "fourth month on this java journey ." + "\n" + "I am looking for fellow newbies who are willing " + "\n" + "to learn and grow together (or advanced programmers " + "\n" + "who will not get annoyed by teaching newbies)." + "\n" + "If you get to this point in the game " + "\n" + "and see this message, hit me up via direct " + "\n" + "messaging, lets create a group where we can learn " + "\n" + "and grow together.");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
thirdRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 10);
System.out.println("Game over, you were so close. Try again");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
secondRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 6);
System.out.println("Game Over. Try again?");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
}while (numberOfAttempts != 3);
System.out.println("Game Over. Try again?");
scan.close();
}
}
The root cause of the problem is using scan.nextInt() inside the catch block. What is happening is guess = scan.nextInt(); just below the try is throwing an exception for non-integer input and the control enters the catch block where it encounters guess = scan.nextInt(); again which tries to consume the Enter from the last input causing the program to crash as Enter is not an int.
How to get rid of it?
You need to make two changes to get rid of the problem:
A. Use guess = Integer.parseInt(scan.nextLine()); in which scan.nextLine() will also consume Enter.
B. Comment out the line, guess = scan.nextInt(); as shown below:
} catch (Exception e) {
System.out.println("Please enter a number.");
//guess = scan.nextInt();
}
This is the exception stack trace you get when you run the code:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at HighLow.main(HighLow.java:137)
When you handle the exception first time the user types in a non-numeric value, the exception gets handled below:
catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
When it reaches guess = scan.nextInt();, the previous non-numeric value is still present in the scanner. And when it tries to get an integer out of the scanner when it has a non-numeric value, it throws another InputMismatchException inside catch that is not handled.

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");
}
}

I'm having an issue with my game

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;
}
}
}
}
}

Categories

Resources