Public class SalesSummary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declarations
float month;
float salesAmt ;
final int SIZE = 12;
String[] MONTH = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
float[] sales = new float[SIZE];
char response;
float total;
float avrg;
do{
System.out.printIn ("Enter month");
month = input.nextFloat();
if (month > 1 || month < 12)
System.out.printIn ("Invalid month");
else
month = month - 1;
System.out.printIn ("Enter sales amount");
salesAmt = input.nextFloat();
sales[month] = (sales[month] + salesAmt);
System.out.printIn("Additional data (Y/N)?");
response = input.next().charAt(0);
total = (sales[0] + sales[1] + sales[2] + sales[3] + sales[4] + sales[5] + sales[6] + sales[7] + sales[8] + sales[9] + sales[10] + sales[11]);
avrg = (total / SIZE);
} while (response == 'y');
for (int x = 0; x < MONTH.length; ++x) {
System.out.println("Sales for " + MONTH[x] + " is: " + sales[x] + "Total is" + total + "Average is: " + avrg) ;
}
}
}
I was looking through the code and can't find why it isn't working. I believe it has something to do the with System.out.printIn() statements and the sales[month] = (sales[month] + salesAmt)
This code won't compile. Need to change the following for it to compile successfully at least:
We are using a float (month) variable as an array index, which is not a valid syntax. Need to change type of month to int.
After changing month to int, input.nextFloat(); needs to be changed to input.nextInt();
System.out.printIn needs to be changed to System.out.println
We can check it's behavior (and compare it with expected output) once it compiles and runs fine.
Related
I am stuck at a part where I am supposed to declare a string variable called "phrase", where it shouldn't loop, all the way through.
to give you an idea my task is: Similar to Option 1 except the user enters 'N' (instead of 'Q') when they are done entering results for the first team. Then, the program inputs a second team name and its results until 'Q' is entered. Outputs two statements, like the statements in option 1 followed by a third statement that says which team is in first place (based on the number of points)
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal // how would I make this appear in the same while loop?
L
L
O
L
L
W
L
L
Q
Sample output:
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
UPDATE:
My code:
else if (option == 2){
int counter = 0;
int totalpoints = 0;
String phrase = keyboard.next();
while(go){
String letter = keyboard.next();
if (letter.equals("W")){
pointsW++;
}
else if (letter.equals("L")){
pointsL++;
}
else if (letter.equals("O")){
pointsO++;
}
counter++;
if (letter.equals("N")){
totalpoints = pointsW + pointsL + pointsO;
counter--;
go = false;
}
}
int counter2 = 0;
int totalpoints2 = 0;
pointsW = 2;
pointsL = 0;
pointsO = 1;
String phrase2 = keyboard.next();
while (go2){
String letter2 = keyboard.next();
if (letter2.equals("W")){
pointsW++;
}
else if (letter2.equals("L")){
pointsL++;
}
else if (letter2.equals("O")){
pointsO++;
}
counter2++;
if (letter2.equals("Q")){
counter2--;
totalpoints2 = pointsW + pointsL + pointsO;
go2 = false;
}
}
System.out.println(phrase + " has played "+counter+" games and has earned "+totalpoints+" points");
System.out.println(phrase2 + " has played "+counter2+" games and has earned "+totalpoints2+" points");
if (totalpoints > totalpoints2){
System.out.println(phrase + " is in first place by "+(totalpoints - totalpoints2) + " points");
}else{
System.out.println(phrase2 + " is in first place by "+(totalpoints2 - totalpoints) + " points");
}
}
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
The issue: This is the output I am getting "Montreal played 8 games and has earned 11 points" where instead it should be "Montreal has played 8 games and has earned 3 points"
The output I am getting
You can reuse the same variables for individual points i.e. pointsW and pointsO because you do not want to retain their values till the end where you are publishing the results. The same is the case with the variable for the loop condition i.e. go and the variable used for inputting win/loss i.e. letter.
You will need arrays or different variables for storing total points, countings, and team name.
import java.util.Scanner;
public class Standings {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
int pointsW = 0;
int pointsO = 0;
String letter;
boolean go = true;
if (option == 2) {
// Variables for total points, counting, and name for the first team
int playedGamesTeamOne = 0;
int teamOnePoints = 0;
String teamOneName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamOne++;
if (letter.equals("N")) {
teamOnePoints = pointsW + pointsO;
playedGamesTeamOne--;
go = false;
}
}
// Reset common variables
go = true;
pointsW = 0;
pointsO = 0;
// Variables for total points, counting, and name for the second team
int playedGamesTeamTwo = 0;
int teamTwoPoints = 0;
String teamTwoName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamTwo++;
if (letter.equals("Q")) {
teamTwoPoints = pointsW + pointsO;
playedGamesTeamTwo--;
go = false;
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned "
+ teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned "
+ teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out
.println(teamOneName + " is in first place by " + (teamOnePoints - teamTwoPoints) + " points");
} else {
System.out
.println(teamTwoName + " is in first place by " + (teamTwoPoints - teamOnePoints) + " points");
}
}
}
}
A sample run:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
you can use this code for option two
Scanner keyboard = new Scanner(System.in);
int teamCounter = 1;
//String[] teamsNames = new String[2];
String teamOneName="";
String teamTwoName="";
//int[] playedGames = new int[2];
int playedGamesTeamOne = 0;
int playedGamesTeamTwo = 0;
//int[] points = new int[2];
int teamOnePoints = 0;
int teamTwoPoints = 0;
boolean firstTimeTeam1 = true;
boolean firstTimeTeam2 = true;
while (teamCounter <= 2) {
if (teamCounter == 1) {
if (firstTimeTeam1) {
teamOneName = keyboard.nextLine();
firstTimeTeam1 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamOnePoints += 2;
playedGamesTeamOne++;
} else if (letter.equals("L")) {
playedGamesTeamOne++;
} else if (letter.equals("O")) {
teamOnePoints += 1;
playedGamesTeamOne++;
} else if (letter.equals("N")) {
teamCounter++;
}
} else {
if (firstTimeTeam2) {
teamTwoName = keyboard.next();
firstTimeTeam2 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamTwoPoints += 2;
playedGamesTeamTwo++;
} else if (letter.equals("L")) {
playedGamesTeamTwo++;
} else if (letter.equals("O")) {
teamTwoPoints += 1;
playedGamesTeamTwo++;
} else if (letter.equals("Q")) {
teamCounter++;
}
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned " + teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned " + teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out.println(teamOneName + " is in first place by " + (teamOnePoints-teamTwoPoints) + " points");
} else {
System.out.println(teamTwoName + " is in first place by " + (teamTwoPoints-teamOnePoints) + " points");
}
A code that gives the multiples of 5 in a given number by the user (x,y). If there is none to display, print "NONE". If there is two to display, separate it with "and". And if theres two or more to display, separate it with comma and "and" in the end of it.
System.out.print("Enter first number: ");
int x = new Scanner (System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
for (;x<=y; x++) {
if(x%5==0) {
System.out.printf("%,d ",x);
}
}
Sample Output:
Enter number: 1
Enter number: 4
The multiples of 5 from 1 to 4: NONE
Sample Output:
Enter number: 8
Enter number: 12
The multiples of 5 from 8 to 12: 10
Sample Output:
Enter number: 1
Enter number: 17
The multiples of 5 from 1 to 17: 5, 10, and 15.
The comma you use in printf isn't a simple character, it's a part of the pattern %,d.
Format String Syntax
If the ',' ('\u002c') flag is given, then the locale-specific grouping separator is inserted by scanning the integer part of the string from least significant to most significant digits and inserting a separator at intervals defined by the locale's grouping size.
You need to move it out of the pattern %d and add a condition to drop a comma for the first matching number.
for (int i = 0; x <= y; x++) {
if (x % 5 == 0) {
System.out.printf("%s%d", (i++ == 0 ? "" : ","), x);
}
}
Or you could write it in a fancy way
String result = IntStream.rangeClosed(x, y)
.filter(i -> i % 5 == 0)
.mapToObj(Integer::toString)
.collect(Collectors.joining(","));
System.out.println(result);
I have shown two working examples that use "," as the only delimiter. It gets a bit trickier for three delimiters ("," and ", and", and " and "). It's a rare case where a switch statement comes in handy.
final List<String> values = IntStream.rangeClosed(x, y)
.filter(i -> i % 5 == 0)
.mapToObj(Integer::toString)
.collect(Collectors.toList());
switch (values.size()) {
case 0:
System.out.println("NONE");
break;
case 1:
System.out.println(values.get(0));
break;
case 2:
System.out.println(String.join(" and ", values));
break;
default:
final String last = values.remove(values.size() - 1);
System.out.println(String.join(", ", values) + ", and " + last);
}
EDIT: I edited my answer to match all sizes of the results-ArrayList:
class Main {
public static void main(String[] args) {
System.out.print("Enter first number: ");
int x = new Scanner(System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner(System.in).nextInt();
System.out.print("The multiples of 5 from " + x + " to " + y + " : ");
ArrayList<Integer> results = new ArrayList<Integer>();
for (; x <= y; x++) {
if (x % 5 == 0) {
results.add(new Integer(x));
}
}
if (results.size() == 0) {
System.out.println("No results to display.");
} else if (results.size() == 1) {
System.out.println(results.get(0));
} else {
for (int i = 0; i < results.size() - 2; i++) {
System.out.print(results.get(i) + ", ");
}
System.out.print(results.get(results.size() - 2));
System.out.println(" and " + results.get(results.size() - 1));
}
}
}
By using the ArrayList, You can store the values and later print them out. The for-loop only prints all elements, but without the last one, which then gets printed with an " and" before it!
I hope you understand how this works.
Let me start with a few tips of your current code. You currently create two Scanners for both your user inputs. It would be best to only create this one, and re-use it. So change:
System.out.print("Enter first number: ");
int x = new Scanner (System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
To:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter first number: ");
int x = scanner.nextInt();
System.out.print("Enter last number: ");
int y = scanner.nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
Next, I would advice to make the step into a variable, so it's easier to change later on (or perhaps ask from the user as input as well):
int step = 5;
...
System.out.print("The multiples of "+step+" from "+x+ " to " +y+ " : ");
...
if(x%step == 0){
...
And now onto your actual problem. Let's first analyse what you want:
You want the separator for most items to be ", " (base case)
You want the separator for the second to last integer in the iteration to be " and "
And the final integer doesn't need any separator anymore, since it's the trailing item
Let's now convert these requirements into code:
for(; x<=y; x++){
if(x%step == 0){
// The last `x` that will be printed, is the x where the difference between y and x
// is smaller than the step-size:
boolean lastNumber = y-x < step;
// The `x` for which we want an " and " separator is the second to last item,
// so the difference between x and y should be smaller than twice the step-size:
boolean showAnd = y-x < 2*step;
// And then we can use these two booleans with a simple ternary-if to determine the
// format we'd want to use in our print:
System.out.printf(lastNumber ? "%d\n"
: showAnd ? "%d and "
: "%d, ",
x);
}
}
Try it online.
Try this, Create a conditional base ending char.
System.out.print("Enter first number: ");
int x = new Scanner(System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
if ((x<5 && y<5) || y/5 == x/5) {
System.out.printf("NONE");
}
else {
while (y > x) {
if (x%5==0) {
System.out.printf("%d", x);
x += 5;
if (x < y) {
if (x + 5 < y) {
System.out.printf(" , ");
} else {
System.out.printf(" and ");
}
}
} else {
x += 1;
}
}
}
This is my solution for this:
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");
int x = scan.nextInt();
System.out.print("Enter last number: ");
int y = scan.nextInt();
String output = "The multiples of 5 from " + x + " to " + y + " : ";
for (; x <= y; x++) {
if (x % 5 == 0) {
output = output + x + ", ";
}
}
output = output.substring(0,output.length() -5) + " and "+output.substring(output.length() -4, output.length()-2);
System.out.println(output);
consider stream api, like
IntStream.range(2, 8).mapToObj(Integer::toString).collect(Collectors.joining(", and "))
How do I get a '-' to appear on my calendar whenever the value for a day of week is empty?
Here is the code:
public static void printCalander(int month, int year) {
String[] monthNames = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
//showing which month is being displayed on the yearly calendar
System.out.println(" " + monthNames[month] + " " + year);
System.out.println("Su Mo Tu We Th Fr Sa");
for (int index = 0; index < obj1; index++) {
System.out.print(" ");
}
//numDays is showing how many days are needed for the calendar following the user input
for (int count = 1; count <= numDays; count++) {
System.out.printf("%2d ", count);
//if the calendar reaches 7 numbers then it will take a new line
if (((count + obj1) % 7 == 0) || (count == numDays)) {
System.out.println("");
}
}//for
}//end of printCalendar
if i understand correctly u need to make an integer array for week days and use it like a controller like this:
String[] array = new String[7];
//take inputs like this:
for(int i = 0; i<7; i++) {
input = k.nextLine();
if(input.equals(""))
array[i] = "-";
continue;
}
array[i] = input;
}
or save inputs in a array and control it. if it has a null element change it to "-".
I am having trouble with this Java program validating user input using a while loop. I must use a while loop. The program works fine until the user enters a number that isn't valid which is when it prints Invalid number entered infinitely. Beginner level sorry, but Thank you for the help!
public class monthName {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
// monthName[0]="January";
// monthName[1]="February";
// monthName[2]="March";
// monthName[3]="April";
// monthName[4]="May";
// monthName[5]="June";
// monthName[6]="July";
// monthName[7]="August";
// monthName[8]="September";
// monthName[9]="October";
// monthName[10]="November";
// monthName[11]="December";
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
}
System.out.println("The Month is: " + monthName[monthNumber - 1]);
}
}
EDIT
After switching the while loop of the code to this:
It still does not give the month name
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
}
System.out.println("The month is: " + monthName);
}
}
Because after you read the number, you start the loop based on value read, but never change the variable, so if while condition is true, it will be true forever. Add another call to nextInt(), like the following:
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
}
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.