EDIT: I have some corrections as an answer. I needed to use another do-while loop for different scenarios in the slot machine. I have figured out the answer to this particular question and have posted the answer for anyone who would like to use this for help.
I have a single do while loop that will not finish. In order to enter the do while loop, I need to enter a number. It will not start unless the user enters something- it will give a mismatch error if one enters a letter which is understandable, but how can I get into the loop without the user entering anything?
Also, would putting in another do loop solve the problem of it not fully running? I'm confused as to the logic of it and my pseudocode is wrong. Thank you.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Slot2
{
public static void main(String[] args) throws IOException
{
int number;
System.out.println ("Welcome to the Slot Machine Simulator!");
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
break;
}
if (option == 1)
{
String username;
double startingTotal = 100.0;
double userTotal = startingTotal;
System.out.print ("\nBefore the game begins, please enter your name: ");
username = keyboard.next( );
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
do **//you have to enter a number here to get the 1st print statement,this is the error**
{
double bet = keyboard.nextDouble();
bet = 0.0;
userTotal = startingTotal - bet;
System.out.print ("You currently have: $%.2f" + startingTotal + "\nHow much would you like to bet?"); **//this is the part of the loop that works**
double winnings = 0.0;
double userFinalTotal = 0.0;
Random generator = new Random();
int slot1 = generator.nextInt(6);
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("-------------------------------");
System.out.println ("" + firstSlot + " " + secondSlot + " " + thirdSlot);
System.out.print ("-------------------------------");
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2fn", userFinalTotal);
}
else
{
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
if ((bet < 0) || (userFinalTotal <= 0))
{
break;
}
while (bet > userFinalTotal)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
} while (userTotal > 0);
}
}
}
Try changing username = keyboard.next( ); to username = keyboard.nextLine( );, I am sure it will work.
There is nothing wrong with your do-while loop.
On top of that, you shouldn't declare these variables inside your while loop.
String username;
double startingTotal = 100.0;
double userTotal = startingTotal;
I have a printwriter statement in a do-while loop in order to print the scores of every user that plays the slot machine. However, I think because of this scores print multiple times when it says to view scores (option 2). Is this because of the variable used, or the fact it is in a do-while loop?
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Slot3
{
public static void main(String[] args) throws IOException
{
System.out.println ("Welcome to the Slot Machine Simulator!");
int option = 0;
//if the user selects a 1 or 2 (does not want to exit) then this loop will run
do
{
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
option = keyboard.nextInt();
keyboard.nextLine();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
keyboard.nextLine();
}
//this will occur if the user selects 1 to play the game
if (option == 1)
{
double money = 100.00;
double bet = 0.00;
double winnings = 0.00;
double score = 0.00;
int count = 0;
System.out.print ("\nBefore the game begins, please enter your name: ");
String username = keyboard.nextLine();
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
System.out.printf("\nYou currently have $%.2f.", 100.00);
do
{
System.out.printf("\n\nHow much would you like to bet? ");
bet = keyboard.nextDouble();
if ((bet < 0) || (money <= 0))
{
break;
}
while (bet > money)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
//create random numbers
Random generator = new Random();
int slot1 = generator.nextInt(6);
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("\n-------------------------------");
System.out.printf ("%-12s%-10s%5s\n", firstSlot , secondSlot , thirdSlot);
System.out.print ("\n-------------------------------");
//check how many of the slots match to calculate the winnings
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else
{
winnings = bet * 0;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
} while ((bet > 0) && (money > 0));
FileWriter fwriter = new FileWriter("scores.txt", true);
PrintWriter outputWriter = new PrintWriter(fwriter);
outputWriter.printf("\n\n%1s%15s" , "Name" , "Score");
outputWriter.printf ("\n\n%1s%15s" , "----" , "-----");
outputWriter.printf ("\n\n%1s%15s" , username , score);
outputWriter.close();
System.out.println("\n\nGame over! Your score has been written to scores.txt, " + username + "!");
} //end of actions for select option 1
//option 2 user wants to read their scores
if (option == 2)
{
File myFile = new File("scores.txt");
//if there are no scores to read
if (!myFile.exists())
{
System.out.println("There are no scores to display at this time.");
continue;
}
File file = new File("scores.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String username = inputFile.nextLine();
System.out.println(username);
}
inputFile.close();
} //close option 2
} while (option != 3); //close 1st do-while loop
if (option == 3)
{
System.out.print ("\nGoodbye!");
System.exit(0);
}
}
}
Int counter = 0, input = 0;
While(counter < 10 && input = 0)
{
Thread.sleep(1000);
Counter++;
input = Scan.nextInt()
}
Not the greatest code I did this from my phone so
Related
I've been working on a slot machine program for class and have been having trouble figuring out how to compare the different "slots" on the machine to determine whether or not there are matches and tell the program how to proceed with calculate winnings. I originally thought of storing each result of my random number generator in a variable and then comparing them but am unsure of how to do this. I am unable to use arrays or lists or anything like that unfortunately. Thanks in advance and sorry if my code looks sloppy.
import java.util.*;
//Start Program
public class Slots
{
public static void main(String[] args)
{ //Start Main
//=====Declare Variables=====
int pool = 0,
won = 0,
slot_disp = 0,
slot0 = 0,
slot1 = 0,
slot2 = 0,
slot3 = 0,
slot4 = 0,
matches = 0,
bet = 0;
boolean again = true;
String msg = "",
ans = "";
Scanner key = new Scanner(System.in);
//=====Welcome and Start=====
System.out.println("\t* * * Welcome to SLOTS * * *");
System.out.print("\nEnter amount of money to play: ");
pool = key.nextInt();
while(again)
{
System.out.print("\nEnter your bet: ");
bet = key.nextInt();
while(bet < 0 || bet > pool)//-----Bet Validation-----
{
System.out.println("\tInvalid bet of : " + (double)bet);
System.out.println("\tFunds available: " + (double)pool);
System.out.print("\tRe-Enter bet : ");
bet = key.nextInt();
}
System.out.print(" ");
for(int cntSlot = 0; cntSlot < 5; cntSlot++)
{
Random rand = new Random();
slot_disp = rand.nextInt(5);
//=====Converting Random Number into Slot Display=====
switch(slot)
{
case 0:
msg = "Cherries";
break;
case 1:
msg = "Oranges";
break;
case 2:
msg = "Plums";
break;
case 3:
msg = "Melons";
break;
case 4:
msg = "Bars";
break;
}
System.out.print(msg + " ");
}//-----End Slot Conversion Loop-----
//=====Comparing Slot Output to Determine Winnings=====
switch(matches)
{
case 2:
won = 0;
break;
case 3:
won = bet * 2;
break;
case 4:
won = bet * 3;
break;
case 5:
won = bet * 4;
break;
default:
won = 0;
}
(double)(pool = (pool - bet) + won);
//=====Displaying the Results=====
if(matches == 5)//-----Jackpot-----
{
System.out.println("\n\n * * * You hit the JACKPOT * * *");
System.out.println("You Won: " + won);
}
if(matches > 2 && match < 5)//-----Winner-----
System.out.println("\n\nYou WIN: " + won);
else
System.out.println("\n\n\nNo matches, sorry you lost.");
if(pool <= 0)//-----Game Over-----
{
System.out.println("\n> > > You ran out of money. < < < ");
System.out.println("\nRestart the game to play again");
again = false;
break;
}
else
System.out.println("\nAvailable money: " + (double)pool);
//=====Asking User if they want to Continue=====
if(pool > 0)
{
System.out.print("\nWould you like to play again (y/n): ");
ans = key.next();
}
if(ans.equalsIgnoreCase("y"))
again = true;
else
again = false;
}
System.out.println("Game over, cash out: " + (double)pool);
System.out.println("\nThanks for playing the Slots!");
} //End Main
}
Use an int[] hits = new int[5]; array to store for each value how often it was selected. in the loop increment hits(slot) += 1;. Later, loop over the array to find the maximum.
I've spent hours on this program trying to figure out how to repeat the main menu to show until the user write 3 (to quit the program).
The program asks the user to enter 2 integer numbers, then Main menu shows to choose from 3 options.
I chose the do while loop to force it show at least once, but i don't know what's my mistake?
package javaapplication33;
import static java.lang.System.exit;
import java.util.Scanner;
public class JavaApplication33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers: ");
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn = showMenu();
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
}
public static int showMenu() {
int optionn = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("--------------");
System.out.println("1.Add the numbers");
System.out.println("2.Multiply the numbers");
System.out.println("3.Quit");
System.out.println("--------------");
System.out.println("Enter your choice:");
optionn = keyboard.nextInt();
return optionn;
}
You could consider just a while loop, instead of a do-while.
int optionn = 0;
while (optionn != 3)
{
optionn = showMenu();
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}
}
Additionally, there's no reason to clear out your optionn variable in your showMenu method.
try this
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
int optionn = showMenu();//SHOWS THE MENU AGAIN
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
Your showmenu() method isnt in your while that why i dosent repeat
The two lines of code that needed fixing - have comments, see below:
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}// End of switch statement
optionn = showMenu(); // <--- changed
} while (optionn != 3); // <--- changed
A couple of mistakes.
First you should be getting the user input inside the do/while loop. Just move your optionn=showMenu() inside the do (That way you can show the options again and allow the user to choose again).
Second you want to keep on looping while optionn!=3 instead of optionn==3 (You want to continue looping if the user doesn't want to exit).
I would also not use exit(0) and also move your exit print statement to inside the loop (So you print it before you exit your function). Something like this:
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn;
do {
optionn = showMenu(); //Allow user to select from menu every iteration
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
System.out.println("Thank you. Good Bye."); //Moved from the bottom
return; //I would use return instead of the exit(0) here.
//exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn != 3); //Make sure this is != not ==
Hope this helps!
For this code, I want to simulate a slot machine and put the username and scores of the games onto a text file titled scores.txt so that if the user selects option 2 they can view their scores.
However, I receive many errors on my FileWriter statement (line is towards the end and marked with a comment), particulary one that I don't understand called unmappable character for encoding CP1252. From everywhere I have checked, I see this error when someone uses a different character like a Japanese character- so why would an error like this come about? I've looked at examples of code but I have not yet learned stream, try and catch, or buffer.
Using filewriter and printwriter can someone explain to me how to create a filewriter object and pass it to a printwriter object correctly, as well as how to correctly read data from that file (scores.txt). Thanks so much in advance, and sorry if this is a simple error.
Specific area of problem:
File file = new File(“scores.txt”); //illegal start of expression
if (!file.exists())
{
file.createNewFile();
}
Scanner inputFile = new Scanner(file);
String line = inputReader.nextLine();
FileWriter fwriter = new FileWriter(“scores.txt”, true); //this is where the error CP1252,
PrintWriter outputWriter = new PrintWriter(file);
outputFile.println(username);
outputFile.println(userFinalTotal);
}
else if (option == 2)
{
if (file.exists())
{
while (inputFile.hasNext())
{
username = inputFile.nextLine();
System.out.println ("Name\n------\n" + name + "\n");
userFinaltotal = inputFile.nextDouble();
System.out.printf("Scores\n------\n$%.2f\n", userFinalTotal);
System.out.println();
inputReader.close();
}
Here is the full program to see where the variables come from.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class SlotsMachine
{
public static void main(String[] args) throws IOException
{
int number;
System.out.println ("Welcome to the Slot Machine Simulator!");
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
break;
}
if (option == 1)
{
String username;
double startingTotal = 100.0;
double userTotal = startingTotal;
System.out.print ("\nBefore the game begins, please enter your name: ");
username = keyboard.next( );
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
do
{
double bet = keyboard.nextDouble();
bet = 0.0;
userTotal = startingTotal - bet;
System.out.print ("You currently have: " + startingTotal + "\nHow much would you like to bet?");
double winnings = 0.0;
double userFinalTotal = 0.0;
if ((bet < 0) || (userFinalTotal <= 0))
{
break;
}
while (bet > userFinalTotal)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
Random generator = new Random();
int slot1 = generator.nextInt(6);
keyboard.nextLine();
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("-------------------------------");
System.out.println ("" + firstSlot + " " + secondSlot + " " + thirdSlot);
System.out.print ("-------------------------------");
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2fn", userFinalTotal);
}
else
{
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
} while (userTotal > 0);
File file = new File(“scores.txt”); //illegal start of expression
if (!file.exists())
{
file.createNewFile();
}
Scanner inputFile = new Scanner(file);
String line = inputReader.nextLine();
FileWriter fwriter = new FileWriter(“scores.txt”, true); //this is where the error CP1252
PrintWriter outputWriter = new PrintWriter(file);
outputFile.println(username);
outputFile.println(userFinalTotal);
}
else if (option == 2)
{
if (file.exists())
{
while (inputFile.hasNext())
{
username = inputFile.nextLine();
System.out.println ("Name\n------\n" + name + "\n");
userFinaltotal = inputFile.nextDouble();
System.out.printf("Scores\n------\n$%.2f\n", userFinalTotal);
System.out.println();
inputReader.close();
}
}
else
{
System.out.println("There are no scores to display at this time.");
}
System.out.println("Actions:");
System.out.print("1. Start a new game\n2. View scores\n3. Exit ");
System.out.println("Please select an action: ");
option = keyboard.nextInt();
}
else if (number == 3)
{
System.out.print ("\nGoodbye!");
System.exit(0);
}
}
}
It compiles now, the only problem is that it prints the scores multiple times.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Slot3
{
public static void main(String[] args) throws IOException
{
System.out.println ("Welcome to the Slot Machine Simulator!");
int option = 0;
//if the user selects a 1 or 2 (does not want to exit) then this loop will run
do
{
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
option = keyboard.nextInt();
keyboard.nextLine();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
keyboard.nextLine();
}
//this will occur if the user selects 1 to play the game
if (option == 1)
{
double money = 100.00;
double bet = 0.00;
double winnings = 0.00;
double score = 0.00;
int count = 0;
System.out.print ("\nBefore the game begins, please enter your name: ");
String username = keyboard.nextLine();
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
System.out.printf("\nYou currently have $%.2f.", 100.00);
do
{
System.out.printf("\n\nHow much would you like to bet? ");
bet = keyboard.nextDouble();
if ((bet < 0) || (money <= 0))
{
break;
}
while (bet > money)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
//create random numbers
Random generator = new Random();
int slot1 = generator.nextInt(6);
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("\n-------------------------------");
System.out.printf ("%-12s%-10s%5s\n", firstSlot , secondSlot , thirdSlot);
System.out.print ("\n-------------------------------");
//check how many of the slots match to calculate the winnings
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else
{
winnings = bet * 0;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
} while ((bet > 0) && (money > 0));
FileWriter fwriter = new FileWriter("scores.txt", true);
PrintWriter outputWriter = new PrintWriter(fwriter);
outputWriter.printf("\n\n%1s%15s" , "Name" , "Score");
outputWriter.printf ("\n\n%1s%15s" , "----" , "-----");
outputWriter.printf ("\n\n%1s%15s" , username , score);
outputWriter.close();
System.out.println("\n\nGame over! Your score has been written to scores.txt, " + username + "!");
} //end of actions for select option 1
//option 2 user wants to read their scores
if (option == 2)
{
File myFile = new File("scores.txt");
//if there are no scores to read
if (!myFile.exists())
{
System.out.println("There are no scores to display at this time.");
continue;
}
File file = new File("scores.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String username = inputFile.nextLine();
System.out.println(username);
}
inputFile.close();
} //close option 2
} while (option != 3); //close 1st do-while loop
if (option == 3)
{
System.out.print ("\nGoodbye!");
System.exit(0);
}
}
}
I am fairly new to Programming and I could really use some help. My problem is as follows. When I run my program it compiles and operates normally if I press 1 on my menu to begin with. The problem I run into is when I press for example option 3 from the menu and it re prompts for option 1. After it re prompts and I press 1 the menu just re prompts for two times and then it will execute the switch (iMenuOption) case '1':. I could really use some assistance, thanks here's my code.
public class Project3
{
public static void main(String[] args)
{
//------------------------------variables--------------------------------
int iMenuOption;
double dAverage;
char cLetterGrade;
String strName;
String strEndingMessage;
String strWelcomeMessage;
int i1 = -1;
int i2 = -1;
int i3 = -1;
dAverage = Utility.calcAverage(i1, i2, i3);
cLetterGrade = Utility.letterGrade(dAverage);
Scanner kb = new Scanner(System.in);
Utility.myInfo();
System.out.print("\n\nWhat's your user name? ");
strName = kb.nextLine();
System.out.print((Utility.createWelcomeMessage(strName)));
System.out.print("\n\n");
Utility.pressEnterToContinue();
System.out.print("\n");
Utility.clearScreen();
iMenuOption = Utility.menuOption();
while (iMenuOption != '6')
{
switch (iMenuOption)
{
case '1':
i1 = Utility.testScore();
i2 = Utility.testScore();
i3 = Utility.testScore();
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
case '2':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
System.out.println("Score 1: " + i1);
System.out.println("Score 2: " + i2);
System.out.println("Score 3: " + i3);
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
case '3':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
dAverage = Utility.calcAverage(i1, i2, i3);
System.out.println("Average: " + dAverage);
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
case '4':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
dAverage = Utility.calcAverage(i1, i2, i3);
cLetterGrade = Utility.letterGrade(dAverage);
System.out.print("Letter grade: " + cLetterGrade);
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
case '5':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
System.out.print("\n");
Utility.calcGPA(cLetterGrade);
System.out.print("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
} //end switch (iMenuOption)
} //end while (iMenuOption !=6)
Utility.clearScreen();
System.out.print(Utility.createEndingMessage(strName));
System.out.print("\n\n");
Utility.pressEnterToContinue();
} //end main()
}
class Utility
{
public static double calcAverage(int i1, int i2, int i3)
{
double dAverage;
final double dTotalTests = 3.0; //
dAverage = ((i1 + i2 + i3)/dTotalTests);
return dAverage;
} //end calcAverage(int, int, int)
public static String createEndingMessage(String strName)
{
String strEndMessage;
strEndMessage = "\t " + strName + " Thank you for using this program";
return strEndMessage;
} //end createEndingMessage(String)
public static String createWelcomeMessage(String strName)
{
String strWelcomeMessage;
strWelcomeMessage = "\n\tHello, " + strName + " this program is made to calculate the" +
" averages of given test scores, display your letter grade, and the "
+ "GPA of the scores. By Cody Buchanan";
return strWelcomeMessage;
} //end createWelcomeMessage(String)
public static double calcGPA(char cLetterGrade)
{
double dGPA;
switch (cLetterGrade)
{
case 'A':
dGPA = 4.0;
System.out.print("GPA: " + dGPA);
break;
case 'B':
dGPA = 3.0;
System.out.print("GPA: " + dGPA);
break;
case 'C':
dGPA = 2.0;
System.out.print("GPA: " + dGPA);
break;
case 'D':
dGPA = 1.0;
System.out.print("GPA: " + dGPA);
break;
case 'F':
dGPA = 0.0;
System.out.print("GPA: " + dGPA);
break;
default:
dGPA = 0.0;
break;
}
return dGPA;
} //end calcGPA(char)
public static void pressEnterToContinue()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("\t Press enter to continue ");
keyboard.nextLine();
} //end pressEnterToContinue
public static void clearScreen()
{
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
} //end clearScreen
public static int testScore()
{
int iTestScore;
Scanner kb = new Scanner(System.in);
System.out.print("Enter a test score: ");
iTestScore = kb.nextInt();
return (iTestScore);
}
public static int menuOption()
{
Scanner kb = new Scanner(System.in);
String strInput;
int iMenuOption;
System.out.println("\n Menu Options");
System.out.println("\t----------------------");
System.out.println("\t1. Enter Test Scores");
System.out.println("\t2. Display Test Scores");
System.out.println("\t3. Display Average");
System.out.println("\t4. Display Letter Grade");
System.out.println("\t5. Display GPA");
System.out.println("\t6. Exit Program");
System.out.println("\t----------------------");
System.out.print("Select one of the options: ");
strInput = kb.nextLine();
iMenuOption = strInput.charAt(0);
while (!(iMenuOption == '1' || iMenuOption == '2' || iMenuOption == '3' || iMenuOption == '4' || iMenuOption == '5' || iMenuOption == '6'))
{
System.out.print("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
System.out.println("\n Menu Options");
System.out.println("\t----------------------");
System.out.println("\t1. Enter Test Scores");
System.out.println("\t2. Display Test Scores");
System.out.println("\t3. Display Average");
System.out.println("\t4. Display Letter Grade");
System.out.println("\t5. Display GPA");
System.out.println("\t6. Exit Program");
System.out.println("\t----------------------");
System.out.print("Select one of the options: ");
strInput = kb.nextLine();
iMenuOption = strInput.charAt(0);
} //end while loop
return iMenuOption;
} //end menuOption()
public static void myInfo()
{
String strName = "\t\tDerek"; //My name
String strClass = "\t\tCSCI"; //The class info
String strDate = "\t\t10/22/13"; //The program's date
String strAssignment = "\tProject"; //The assignment name
System.out.println("Author:\t\t" + strName);
System.out.println("Class:\t\t" + strClass);
System.out.println("Date:\t\t" + strDate);
System.out.println("Assignment:\t\t" + strAssignment);
}
public static char letterGrade(double dAverage)
{
char cLetterGrade; //To hold the letter grade character value
if (dAverage >= 90 && dAverage <= 100)
{
cLetterGrade = 'A';
}
else if (dAverage >= 80 && dAverage < 90)
{
cLetterGrade = 'B';
}
else if (dAverage >= 70 && dAverage < 80)
{
cLetterGrade = 'C';
}
else if (dAverage >= 60 && dAverage < 70)
{
cLetterGrade = 'D';
}
else
{
cLetterGrade = 'F';
}
return cLetterGrade;
} //end letterGrade(double)
} //end Utility class
In menuOption:
iMenuOption = strInput.charAt(0)
which you are saying to return you the first character of the string. Then you are assigning it to an int. So Char '1' does != integer 1.
Fix that and you are good =)
Could just do:
iMenuOption = Integer.valueOf(strInput.charAt(0));
should be right as rain.
Since the iMenuOption is declared as an int,in the switch - cases- we will have to specify n integer value, rather than a char (displayed in ' ' ).
What happens is, when a char value is being compare against, it actually compares against its ascii value.
while (iMenuOption != '6')
{
switch (iMenuOption)
{
case '1': (change to case 1: ) (not case '1')
....
break;
case '2': (This should be case 2:)
....
break;
case '3': (This should be case 3:)
....
break;
case '4': (This should be case 4:)
....
break;
case '5': (This should be case 5:)
....
break;
}
} //end switch (iMenuOption)
Also try including a default case for the switch statement, which will execute incase an invalid value that reaches the switch.
replace
iMenuOption = Utility.menuOption();
while (iMenuOption != '6')
with
while ((iMenuOption = Utility.menuOption()) != '6')
Having trouble with this the whole day. Please help me. I can't get the problem to display
The output shows
PROBLEM NUMBER 1
Answer:0
Correct....
PROBLEM NUMBER 2
Answer:1
Wrong....
It must show:
PROBLEM NUMBER 1
10 + 11 = ?
Answer: 21
Correct...*/
import java.util.Random;
import java.util.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class MathIsSuperFun1{
Scanner input = new Scanner(System.in);
int correctAnswers;
int randomNum1;
int randomNum2;
int choice;
int corrrectAnswers, wrongAnswers;
String playerName ="";
int operation;
int userAnswer;
int correctAnswer = 0;
int userRemainder, correctRemainder;
int x = 0;
int temporaryNum1, temporaryNum2;
int range;
int randomNumber;
public static void main (String args[]){
MathIsSuperFun1 lab = new MathIsSuperFun1();
lab.init();
}
public void init(){
getName();
pickDifficulty();
pickOperation();
for(int x = 0; x < 10; x++)
{
System.out.println("\t\t\t~~~~~~~PROBLEM NUMBER" + (x + 1) + "~~~~~~~~");
assignNum();
getProblem();
checkAnswer();
}
}
//GET PLAYER NAME USING PANE
public static String getName(){
String playerName;
playerName = JOptionPane.showInputDialog(null, "Welcome!\nEnter your name and press OK.", "Math Is Super Fun!", JOptionPane.QUESTION_MESSAGE);
System.out.println("Do your best," + playerName + "!");
return playerName;
}
//GET PROBLEM BASED ON OPERATION
public void getProblem(){
switch(operation){
case 1:
System.out.println(randomNum1 + "+" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 + randomNum2;
break;
case 2:
System.out.println(randomNum1 + "-" + randomNum2 + "= ?\n");
correctAnswer = randomNum1-randomNum2;
break;
case 3:
System.out.println(randomNum1 + "*" + randomNum2 + "= ?\n");
correctAnswer = randomNum1*randomNum2;
break;
case 4:
System.out.println(randomNum1 + "/" + randomNum2 + "= ?\n");
correctAnswer = randomNum1/randomNum2;
correctRemainder = randomNum1%randomNum2;
break;
}
System.out.print("Answer: ");
userAnswer = input.nextInt();
if(operation == 4){
System.out.print("Remainder: ");
userRemainder = input.nextInt();
}
return 0;
}
//PICK DIFFICULTY USING DIALOG
public void pickDifficulty(){
int choice = 0;
System.out.println("1 - Child's Play\n2 - No Sweat\n3 - Bitter\n4 - Cold-blooded\n5 - Brutal\n6 - Genius");
choice = input.nextInt();
}
//PICK OPERATIONS
public void pickOperation(){
int operation = 0;
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
//GET NUMBER RANGE BASED ON DIFFICULTY
public int numberRange(){
int range = 0;
switch(choice){
case 1:
range = 100;
break;
case 2:
range = 1000;
break;
case 3:
range = 10000;
break;
case 4:
range = 100000;
break;
case 5:
range = 1000000;
break;
case 6:
range = 10000000;
break;
}
return range;
}
//GET CORRECT RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public void correctResponse(){
String responseCorrect = "";
switch (getRandom(5)){
case 1:
responseCorrect = "Correct. Keep up the good work!";
break;
case 2:
responseCorrect = "Correct. Keep aiming higher!";
break;
case 3:
responseCorrect = "Correct. Well done!";
break;
case 4:
responseCorrect = "Correct. Nice work!";
break;
case 5:
responseCorrect = "Correct. We're almost there!";
break;
}
System.out.println(responseCorrect);
correctAnswers += 1;
}
//GET WRONG RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public String wrongResponse(){
String responseWrong = "";
switch (getRandom(5)){
case 1:
responseWrong = "Wrong. Don't give up!";
break;
case 2:
responseWrong = "Wrong. You can do it!";
break;
case 3:
responseWrong = "Wrong. Try again puny human!";
break;
case 4:
responseWrong = "Wrong. You must be really weak at math!";
break;
case 5:
responseWrong = "Wrong. I pity you!";
break;
}
System.out.println(responseWrong);
System.out.println("The correct answer is:" + correctAnswer);
if(operation == 4)
System.out.println("Correct Remainder: " + correctRemainder);
return responseWrong;
}
public void checkAnswer(){
if(operation != 4 && userAnswer == correctAnswer){
correctResponse();
}
else if(operation == 4 && userAnswer == correctAnswer && userRemainder == correctRemainder){
correctResponse();
}
else{
wrongResponse();
}
}
public void assignNum(){
int temporaryNum1 = getRandom(numberRange());
int temporaryNum2 = getRandom(numberRange());
while(operation == 4 && temporaryNum1 == 0){
temporaryNum1 = getRandom(numberRange());
}
while(operation == 4 && temporaryNum2 == 0){
temporaryNum2 = getRandom(numberRange());
}
if(temporaryNum1 > temporaryNum2)
{
randomNum1 = temporaryNum1;
randomNum2 = temporaryNum2;
}
else
{
randomNum1 = temporaryNum2;
randomNum2 = temporaryNum1;
}
}
public int getRandom(int range){
randomNumber = (int)Math.floor((Math.random()*range)+1);
return randomNumber;
}
}
The reason your questions are not outputting is simple.
public void pickOperation(){
int operation = 0;
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
You are creating a local variable, operation, and assigning the input value to it. This means that the field, operation, is never set, so when it comes to the switch statement in your getProblem method, it doesn't output anything because it doesn't match the switch statement.
To fix this, simply remove the int operation = 0; declaration.
Edit
Just noticed the same problem with your pickDifficulty method. I would strongly recommend you have a look at this tutorial on scope in Java.
Explanation of your Problem
Okay. So let's look at your code:
public void pickOperation(){
int operation = 0;
// Declare an int, called 'operation'.
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
// Set the newly declared value to an int from the keyboard.
operation = input.nextInt();
}
As soon as this method is finished, the value inside operation is destroyed. The reason why it isn't staying in your field int operation, is because you declared a more local operation variable. By removing the int operation = 0; at the start of this method, you force the JVM to look for the next available variable named operation in your class, which is in the field. That's why, when you remove the first assertion statement, your value for operation will stick around.
the problem is : int operation = 0; you need to take the value of the operation in operation variable which you create it in Main
Try this :
import java.util.Random;
import java.util.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class Main {
Scanner input = new Scanner(System.in);
int correctAnswers;
int randomNum1;
int randomNum2;
int choice;
int corrrectAnswers, wrongAnswers;
String playerName = "";
int operation;
int userAnswer;
int correctAnswer = 0;
int userRemainder, correctRemainder;
int x = 0;
int temporaryNum1, temporaryNum2;
int range;
int randomNumber;
public static void main(String args[]) {
Main lab = new Main();
lab.init();
}
public void init() {
getName();
pickDifficulty();
pickOperation();
for (int x = 0; x < 10; x++) {
System.out.println("\t\t\t~~~~~~~PROBLEM NUMBER" + (x + 1) + "~~~~~~~~");
assignNum();
getProblem();
getAnswers();
checkAnswer();
}
}
//GET PLAYER NAME USING PANE
public static String getName() {
String playerName;
playerName = JOptionPane.showInputDialog(null, "Welcome!\nEnter your name and press OK.", "Math Is Super Fun!", JOptionPane.QUESTION_MESSAGE);
System.out.println("Do your best," + playerName + "!");
return playerName;
}
//GET PROBLEM BASED ON OPERATION
public void getProblem() {
switch (operation) {
case 1:
System.out.println(randomNum1 + "+" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 + randomNum2;
break;
case 2:
System.out.println(randomNum1 + "-" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 - randomNum2;
break;
case 3:
System.out.println(randomNum1 + "*" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 * randomNum2;
break;
case 4:
System.out.println(randomNum1 + "/" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 / randomNum2;
correctRemainder = randomNum1 % randomNum2;
break;
}
System.out.print("Answer: ");
userAnswer = input.nextInt();
if (operation == 4) {
System.out.print("Remainder: ");
userRemainder = input.nextInt();
}
// return 0;
}
//PICK DIFFICULTY USING DIALOG
public void pickDifficulty() {
System.out.println("1 - Child's Play\n2 - No Sweat\n3 - Bitter\n4 - Cold-blooded\n5 - Brutal\n6 - Genius");
choice = input.nextInt();
}
//PICK OPERATIONS
public void pickOperation() {
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
//GET NUMBER RANGE BASED ON DIFFICULTY
public int numberRange() {
int range = 0;
switch (choice) {
case 1:
range = 100;
break;
case 2:
range = 1000;
break;
case 3:
range = 10000;
break;
case 4:
range = 100000;
break;
case 5:
range = 1000000;
break;
case 6:
range = 10000000;
break;
}
return range;
}
//GET CORRECT RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public void correctResponse() {
String responseCorrect = "";
switch (getRandom(5)) {
case 1:
responseCorrect = "Correct. Keep up the good work!";
break;
case 2:
responseCorrect = "Correct. Keep aiming higher!";
break;
case 3:
responseCorrect = "Correct. Well done!";
break;
case 4:
responseCorrect = "Correct. Nice work!";
break;
case 5:
responseCorrect = "Correct. We're almost there!";
break;
}
System.out.println(responseCorrect);
correctAnswers += 1;
}
//GET WRONG RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public String wrongResponse() {
String responseWrong = "";
switch (getRandom(5)) {
case 1:
responseWrong = "Wrong. Don't give up!";
break;
case 2:
responseWrong = "Wrong. You can do it!";
break;
case 3:
responseWrong = "Wrong. Try again puny human!";
break;
case 4:
responseWrong = "Wrong. You must be really weak at math!";
break;
case 5:
responseWrong = "Wrong. I pity you!";
break;
}
System.out.println(responseWrong);
System.out.println("The correct answer is:" + correctAnswer);
if (operation == 4) {
System.out.println("Correct Remainder: " + correctRemainder);
}
return responseWrong;
}
public void checkAnswer() {
if (operation != 4 && userAnswer == correctAnswer) {
correctResponse();
} else if (operation == 4 && userAnswer == correctAnswer && userRemainder == correctRemainder) {
correctResponse();
} else {
wrongResponse();
}
}
public void assignNum() {
int temporaryNum1 = getRandom(numberRange());
int temporaryNum2 = getRandom(numberRange());
while (operation == 4 && temporaryNum1 == 0) {
temporaryNum1 = getRandom(numberRange());
}
while (operation == 4 && temporaryNum2 == 0) {
temporaryNum2 = getRandom(numberRange());
}
if (temporaryNum1 > temporaryNum2) {
randomNum1 = temporaryNum1;
randomNum2 = temporaryNum2;
} else {
randomNum1 = temporaryNum2;
randomNum2 = temporaryNum1;
}
}
public int getRandom(int range) {
randomNumber = (int) Math.floor((Math.random() * range) + 1);
return randomNumber;
}
private void getAnswers() {
////////////////Not yet implemented";
}
}