Adding a counter to a java program with different methods - java

My program is a math game and will ask the user different questions in different levels. I would like to use a money rewards system that whenever they get one question right, $1000 will be added to their prize. I have tried to do this, however the money doesn't add when an answer is answered correctly. Help please on how I can go about fixing this.
import javax.swing.*;
import java.io.*;
public class mathGame
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed by the user
int money = 0;
String player = JOptionPane.showInputDialog(null, "Welcome to... \n - Are YOU Smarter Than a 12 Year Old? - \n Please enter your name to begin!", "Welcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Hi " + player + ", " + " let's see if you are really smarter than a 12 year old. \n This games consists of 3 levels of difficulty. \n Answer all 4 questions in each level and earn $500, 000! \n If you get an answer wrong you lose $100, you go home EMPTY HANDED if your money reaches 0!");
Object[] options = {"Yes!", "No way!"};
int x = JOptionPane.showOptionDialog(null,"Are you ready to play?","Start?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (x == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "...Level: 1...");
JOptionPane.showMessageDialog(null, "Your first level consists of addition and substraction of 2 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int y = 0; y <= 3; y++){
addition();
subtraction();
}
JOptionPane.showMessageDialog(null, "...Level: 2...");
JOptionPane.showMessageDialog(null, "Your second level consists of addition and substraction of 3 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int z = 0; z <= 6; z++){
addSub();
}
}
else if (x == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
public static int addition()
{
int money = 0;
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
String sumA = JOptionPane.showInputDialog(null, firstNum + "+" + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int sum = Integer.parseInt (sumA);
int realSum = firstNum + secondNum;
if (sum == realSum){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (sum != realSum){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return sum;
}
public static int subtraction ()
{
int money =0;
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
if (firstNum < secondNum){
firstNum = secondNum;
secondNum = firstNum;
}
String differenceA = JOptionPane.showInputDialog(null, firstNum + " - " + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int difference = Integer.parseInt (differenceA);
int realDifference = firstNum - secondNum;
if (difference == realDifference){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (difference != realDifference){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return difference;
}
public static int addSub ()
{
int money = 0;
int signNum = (int)(Math.random()*1);
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
int thirdNum = (int)(Math.random()*10);
String answerA = JOptionPane.showInputDialog(null, firstNum + " + " + secondNum + " - " + thirdNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int answer = Integer.parseInt (answerA);
int realAnswer = firstNum + secondNum - thirdNum;
if (answer == realAnswer){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (answer != realAnswer){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return answer;
}
}

Don't do the math with local variables. Instead declare money as a instance variable:
public class mathGame
{
private static int money = 0;
(...)
Remove all the other int money = 0; from the code except the one above.

You have to declare you money variable as a class variable. If you see each time you call a method, you create a new variable money and set it to 0.
public class mathGame
{
static int money = 0;
Remove all the initializations of money (int money = 0;) in your method and it will works.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class mathGame
{
private static int money = 0;
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed by the user
String player = JOptionPane.showInputDialog(null, "Welcome to... \n - Are YOU Smarter Than a 12 Year Old? - \n Please enter your name to begin!", "Welcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Hi " + player + ", " + " let's see if you are really smarter than a 12 year old. \n This games consists of 3 levels of difficulty. \n Answer all 4 questions in each level and earn $500, 000! \n If you get an answer wrong you lose $100, you go home EMPTY HANDED if your money reaches 0!");
Object[] options = {"Yes!", "No way!"};
int x = JOptionPane.showOptionDialog(null,"Are you ready to play?","Start?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (x == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "...Level: 1...");
JOptionPane.showMessageDialog(null, "Your first level consists of addition and substraction of 2 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int y = 0; y <= 3; y++){
addition();
subtraction();
}
JOptionPane.showMessageDialog(null, "...Level: 2...");
JOptionPane.showMessageDialog(null, "Your second level consists of addition and substraction of 3 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int z = 0; z <= 6; z++){
addSub();
}
}
else if (x == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
public static int addition()
{
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
String sumA = JOptionPane.showInputDialog(null, firstNum + "+" + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int sum = Integer.parseInt (sumA);
int realSum = firstNum + secondNum;
if (sum == realSum){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (sum != realSum){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return sum;
}
public static int subtraction ()
{
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
if (firstNum < secondNum){
firstNum = secondNum;
secondNum = firstNum;
}
String differenceA = JOptionPane.showInputDialog(null, firstNum + " - " + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int difference = Integer.parseInt (differenceA);
int realDifference = firstNum - secondNum;
if (difference == realDifference){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (difference != realDifference){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return difference;
}
public static int addSub ()
{
int signNum = (int)(Math.random()*1);
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
int thirdNum = (int)(Math.random()*10);
String answerA = JOptionPane.showInputDialog(null, firstNum + " + " + secondNum + " - " + thirdNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int answer = Integer.parseInt (answerA);
int realAnswer = firstNum + secondNum - thirdNum;
if (answer == realAnswer){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (answer != realAnswer){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return answer;
}
}
You need to make an instance variable. Also in each method you set the money = 0 so each time you called the method it turned to 0. Posted code works.

You are creating a new local money variable everytime you call a method so it will always start at 0 each call.
int money = 0;
You need to remove this statement at the start of addition, subtractionand addsub

The money variables you are using are local within each method (which means they are gone as soon as the methods exit). You need to get rid of all those money variables and declare one instance variable:
public class mathGame
{
/* Class variable, declared outside of any method */
static protected int money = 0;
...
/* Methods declaration here */
...
}
More info on Java variables.
It is probably a better idea, to not have all your methods and variables static and work with an Instance of the class instead.
Difference between Instance and Class variables.

Related

How to loop quiz a certain amount of times and add lives, Java

I have a math quiz game I am making and I am not sure how to loop it, let's say 50 times. It ends after answering only 2 questions. I also want to add lives so after you get three questions wrong it ends the program. How am I able to do this?
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}else {
System.out.println("Wrong!");
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
System.out.println("You got " + correct + " correct answers.");
After the int correct = 0;
add a lives counter.
eg:
int lives =3;
then start a while loop
while(lives > 0){
reduce the lives if a question is incorrect (where you put "wrong!" message)
lives--;
at the end of the while loop (before no of correct answers is printed out)
remember to put the last }
This will keep looping till you lose your lives
A couple things:
-There are multiple java structures which allow you to loop. The main loops out there in any kind of programming language are for loop, while loop, and do-while loop (uncommon)
-You can create lives by defining a variable and checking it in every iteration (an iteration is each "run" through the code of a loop).
Your code after implementing this 2 things would look like this:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
int lives = 3;
//The for loop is read as: having i equal 25 and the variable lives, iterate if i is lower than 25 AND lives is higher than 0. After an iteration, add 1 to i;
for (int i=25, lives; i<25 && lives > 0; i++) {
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
} else {
System.out.println("Wrong!");
lives--;
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
lives--;
} //Forgot this bracket
} //Closes the for loop
System.out.println("You got " + correct + " correct answers.");
See if below example works as you intend. Here I have given the loop count as 5. So there will be 5 "addition" questions and 5 "multiplication" questions.
I'm printing the question number also. So, now the output is more clear.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int correct = 0;
for (int i = 0; i < 5; i++) {
int Number1 = (int) (20 * Math.random()) + 1;
int Number2 = (int) (20 * Math.random()) + 1;
System.out.println("Question " + (i*2+1));
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
System.out.println("Question " + (i*2+2));
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
}
System.out.println("You got " + correct + " correct answers.");
}
}

Trying to keep new ending balance if while loop repeats

I have to create a game that prompts the user to put in a starting balance and then place a bet. Then they win or lose and their balance is added or subtracted accordingly. My problem is that I don't know how to make the program remember the final balance before starting over in the while loop if the player wants to play again. My balance stays as the original first balance entered when the user is prompted. I'm sorry if this is a repeat, but I couldn't find a question like this and I've been searching for over an hour. Thanks in advance.
import static java.lang.Math.*;
import java.util.Scanner;
public class BetGame
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int die1, die2;
boolean looping = true;
System.out.println("Please enter your starting balance in whole dollars:");
double balance = in.nextDouble();
System.out.println("Your beginning balance is " + balance + ", good luck!!");
int guess = 0;
double bet2 = 0;
double endingBalance = 0;
while(looping) {
while (guess < 3) {//to allow the user to do this only 3 times
System.out.println("Enter a valid bet:");
double bet = in.nextDouble();
if (bet >= balance || bet >= endingBalance){
System.out.println("That is more than your balance.");
}
else if (bet < balance || bet < endingBalance) {
bet2 = 0 + bet;
break;
}
guess++;
if (guess == 3) {
looping = false;
System.out.println("You have entered three invalid bets in a row. Please leave the casino.");
}
}
die1 = RollDie();
die2 = RollDie();
int sum = die1 + die2;
if (2 <= sum && sum <= 6) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a win!");
endingBalance = balance + bet2;
}
else if (7 <= sum && sum <= 12) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a lose!");
endingBalance = balance - bet2;
}
System.out.println("Your balance is " + endingBalance);
System.out.println("Do you want to roll again?");
String answer = in.next();
if ((answer.equals("n")) || (answer.equals("N"))) {
looping = false;
}
}
System.out.println("Your balance is " + endingBalance + ". Better luck next time! Have a wonderful evening!");
}
static int RollDie()
{
int min = 1;
int max = 6;
return myRandomInteger(min, max);
}
static int myRandomInteger(int min, int max)
{
double range = max - min + 1.0;
int randomNum = (int)(range * Math.random()) + min;
return randomNum;
}
}
You can store the balance in a variable
double balance = in.nextDouble();
double originalBalance = balance;

Write a Java program that generates five questions and reports the number of the correct answers after a student answers all five questions

I'm new at java, and i am trying to write a code that displays the number of questions they got right, not that they got each one right. When i try to run it, i can't make it display the number of questions they got right. For example, i want it to say "You got 4 out of 5 questions correct!", depending on how many they got right. This is what i have so far:
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while (count < 5){
int number1 = (int)(Math.random() * 100);
int number2 = (int)(Math.random() * 100);
System.out.println("What is " + number1 + " + " + number2 + "?");
count++;
int answer = number1 + number2;
int guess = sc.nextInt();
boolean correct = guess == answer;
if (guess == answer){
}
System.out.println("You got " + correct + " correct");
}
}
}
There is a slight change required in your logic.
int correctAnswer = 0; // this is a new variable you have to introduce before while (count < 5){
if (guess == answer){
correctAnswer++;
}
// This line should be outside of while loop as well..
System.out.println("You got " + correctAnswer + " out of " + count + " questions correct");
There are two problems in your code:
(1) no count of correct answers;
(2) no print after you're done.
You do have a print while the test is in progress, but that's not when you said you want to print. Try these two changes: count inside the if statement and print after the loop,.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while (count < 5){
...
boolean correct = guess == answer;
if (guess == answer){
correct++;
}
}
System.out.println("You got " + correct + " out of " + count " questions correct");
}

Creating 1 decimal place

So I am more or less completely done with this code that runs a guessing game. At the end it prints the total results for all games played. This includes total games, total guesses, avg guesses/game and the best score. I have it all worked out except i need the avg guesses/game to show 1 decimal place but the System.out.printf("Guesses/game = %.1f") isn't working and idk why
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
int bestGame = Integer.MAX_VALUE;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) { //repeats until user enters a statement besides y when asked to play again
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
bestGame = Math.min(bestGame, numberOfTries);
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.printf("Guesses/game = ", totalGuesses/totalGames);
System.out.println("Best game = " + bestGame);
}
}
both totalGuesses and totalGames are integers, so when you divide them you get an integer, whereas %f needs a floating point number.
Instead cast one to a floating point number for floating point division:
totalGuesses/(double)totalGames
Try a decimal formatter if for some reason you're simply getting the wrong output:
DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(avgGuesses)); //or whatever your var name is

Global Int variable method for multiple methods

I have to set up a math program that supplies random questions to the user based on their year level, and if they're doing well raise the difficulty. I've set up this code here that runs through questions and if they meet the requirements it displays the harder questions, however if "i" that i use to determinate how member questions they've done if separate the program will run the harder questions then go back and finish the easier questions
So basically I've tried to write a method for global "i" which all other methods will use, however when i replace "i" with the method it stops counting and continues to display questions infinitely and i don't know how to fix this.
import java.util.Scanner;
import java.util.*;
import java.util.Date;
public class Quiz {
public static void main(String[] args) {
int answer;
int correct;
double current_score = 100.00;
// int i = 0;
while (questionsDone() < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
System.out.print("What is the sum of" + " ");
System.out.print(random);
System.out.print(" + " + random2 + " ");
System.out.print("=" + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10.00);
}
System.out.println("Your current percentage is " + current_score); // end of result display
// i++; // raise number of questions given by 1
if (questionsDone() == 5 && current_score >= 75) { // code to move up or down year level
System.out.println("You are doing well! Let's increase the difficulty a little");
Year1_10Questions();
}
}
}
public static void Year1_10Questions() {
int i = 0;
int answer;
int correct;
double current_score = 100.00;
while (i < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
int random3 = (int) (Math.random() * 2 + 1);
String operator = "";
switch (random3) {
case 1:
operator = "+";
break;
case 2:
operator = "-";
break;
}
System.out.print("What is the sum of ");
System.out.print(" " + random + " ");
System.out.print(operator + " ");
System.out.print(random2 + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
if (random3 == 1) {
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
} else if (random3 == 2) {
correct = random - random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
}
System.out.println("Your current percentage is " + current_score); // end of result display
i++; // raise number of questions given by 1
}
} // end of year 1_10 questions
public static int questionsDone() {
int i = 0;
i++;
return i;
}
}
Since all the methods are in the same class, you can define i on class level:
public class Quiz {
static int i;
...
}

Categories

Resources