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!
Related
I am trying to program a menu for my calculator. I do not know how to get out of my inner loop and get back to my outer loop once I have executed the inner loop. I have to finish the whole case of the inner loop before I can get back to the outer loop. Is there a way that I can go back and forth of the nested switch whenever I want to? and when I execute my outer switch case 3, it executes infinitely. Maybe because it's inside a loop.
import java.util.Scanner;
public class MainInterface {
static Scanner input = new Scanner(System.in);
static boolean hasRun = false;
public static void main(String args[])
{
Calculator Mycal = new SimpleCalculator();
ScientificCalculator Mycal2 = new ScientificCalculator();
mainMenu();
int choice = input.nextInt();
do {
System.out.println("\n");
switch(choice) // outer switch
{
case 1: simpleCalculatorMenu();
int choice2 = input.nextInt();
switch(choice2) // inner switch
{
case 1: //ADDITION
System.out.println("ADDITION");
System.out.println("\n");
System.out.println("Enter first number: ");
float x = input.nextFloat();
System.out.println("Enter second number: ");
float y = input.nextFloat();
System.out.println("\n");
System.out.println("The sum of " + x + " " + y + " is " + Mycal.add(x, y));
System.out.println("\n");
System.out.println("Would you like to return to the main menu?");
System.out.println("\n");
System.out.println("Enter 1. to return 2. to exit");
choice = input.nextInt();
break;
}
break;
case 2: System.out.println("SCIENTIFIC CALCULATOR");
System.out.println("\n");
System.out.println("1. power(x, pow) 2. sin(xDeg) 3. cos(xDeg) 4. tan(xDeg)");
System.out.println("\n");
System.out.println("5. pi() 6. fact(x) ");
int choice3 = input.nextInt();
switch(choice3) {
case 1:
System.out.println("POWER");
System.out.println("\n");
System.out.println("Enter first number: ");
double x = input.nextDouble();
System.out.println("Enter second number: ");
double y = input.nextDouble();
System.out.println("\n");
System.out.println("The power of " + x + " to the power of " + y + " is " + Mycal2.power(x, y));
System.out.println("\n");
System.out.println("Would you like to return to the main menu?");
System.out.println("\n");
System.out.println("Enter 1. to return 2. to exit");
choice = input.nextInt();
break;
case 2:
}
break;
case 3: mainMenu();
break;
case 4: System.exit(choice);
break;
}
} while(choice != 0);
}
public static void simpleCalculatorMenu () {
System.out.println("SIMPLE CALCULATOR");
System.out.println("\n");
System.out.println("1. Addition 2. Subtraction 3. Multiplication 4. Division");
System.out.println("\n");
System.out.println("5. Squared Root 6. Squared 7. Cube 8. Discount ");
}
public static void mainMenu () {
System.out.println("What calculator do you want to use?");
System.out.println("\n");
System.out.println("1. Simple Calculator \t 2. Scientific Calculator");
}
}
by adding label you can try like this
OUTER:
switch(condition1) {
case x:
switch(condition2) {
case y:
System.out.println("hello");
break OUTER;
}
}
I'm trying to error proof my program that basically works as a mini calculator. But I have no idea how to write a "Catch" statement that would detect when the user enters a case number that doesn't exist, in my case anything that is negative or > 4
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
}
}
catch(Exception e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
} ```
Why do you want to throw an Exception unnecessarily? I suggest you just put a default case in your switch with the required error message. Also, move the input part inside the loop, so that it continues to take input.
I also suggest you use nextLine() instead of nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = 0, n = 1;
boolean valid;
do {
do {
valid = true;
try {
operacija = Integer.parseInt(operacijai.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter an integer only.");
valid = false;
}
} while (!valid);
switch (operacija) {
case 1:
System.out.println("addingMethod()");
n = 2;
break;
case 2:
System.out.println("subtractingMethod()");
n = 2;
break;
case 3:
System.out.println("multiplyingMethod()");
n = 2;
break;
case 4:
System.out.println("dividingMethod()");
n = 2;
break;
default:
System.out.println("Invalid input");
}
} while (n == 1);
}
}
A sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
5
Invalid input
Another sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()
You can also handle the use case in default
It is totally upto your use-case how you are handling the exception, you can also create your custom exception and throw from default
something like:
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
default:
System.out.print("Enter a correct number!")
throw new CustomException();
}
}
catch(CustomException e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
}
Figured out a clean way of doing this with default case.
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija;
do {
operacija = operacijai.nextInt();
switch (operacija) {
case 1:
addingMethod();
break;
case 2:
subtractingMethod();
break;
case 3:
multiplyingMethod();
break;
case 4:
dividingMethod();
break;
default:
System.out.print("Enter a correct number!");
}
} while(operacija < 1 || operacija > 4);
operacijai.close();
}
This is a simple calculator that I need to get functioning with basic commands. The goal of this project is to program exceptions (very easy) but, I for the life of me, can not figure this out. I have looked everywhere.
Whether it's an if/else statement or a Switch/Case statement, the thrid statement always get skipped. When a user inputs "m" it is supposed to save the value of the calculation to a placeholder variable to be able to be recalled (Again, super simple). I added a default case statement to the addition section and added my save method to the default statement and it works perfectly. Every other command (r for recall, c for clear, and e for exit) also work great. m for save does not at all.....
import java.util.Scanner;
public class Calculator {
public static Scanner input = new Scanner(System.in);
public static double placeHolder;
public static void clear() {
System.out.println("Save has been deleted, Screen has been cleared.");
}
public static void end() {
System.out.println("Program ended..");
input.close();
System.exit(0);
}
public static void save(double initValue) {
System.out.println("Number saved!");
placeHolder = initValue;
}
public static void recall() {
if (placeHolder != 0){
System.out.println("Memory Place Holder Set To: " + placeHolder);
}
else {
System.out.println("There is no data saved.");
}
}
public static void commands() {
System.out.println("e = end | c = clear | m = save | r = recall | o = continue");
String command = input.nextLine();
if (command.equals("e")){
end();
}
else if (command.equals("c")){
clear();
}
else if (command.equals("r")){
recall();
}
}
public static void main(String[] args) {
boolean loop = true;
while (loop == true){
commands();
System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
String function = input.nextLine();
System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
double n1 = input.nextDouble();
System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
double n2 = input.nextDouble();
//=======================
// Addition
//=======================
if (function.equals("+")){
double sum = n1+n2;
System.out.println(n1+"+"+ n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
default:
System.out.println("Default");
save(sum);
break;
}
}
//=======================
// Subtraction
//=======================
else if (function.equals("-")){
double sum = n1-n2;
System.out.println(n1 + "-" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Multiplication
//=======================
else if (function.equals("*")){
double sum = n1*n2;
System.out.println(n1 + "*" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Division
//=======================
else if (function.equals("/")){
double sum = n1/n2;
System.out.println(n1 + "/" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Mod
//=======================
else if (function.equals("%")){
double sum = n1%n2;
System.out.println(n1 + "%" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
}
//=======================
// Dictate loop duration:
//=======================
System.out.println("Would you like to continue? (Y|N): ");
String ans = input.nextLine();
if (ans.equals("N") || ans.equals("n")){
System.out.println("Closing Program");
loop = false;
end();
}
}
}
The main code in question is this: I know the rest don't have a default or break statement. This one does and I am debugging and trying to figure out why the m fails. Right now if you him m, it just goes to the default case statement which, does not solve the issue.
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
default:
System.out.println("Default");
save(sum);
break;
=========================================================================
Here is the Fix for anyone looking at this post after the fact:
public static void main(String[] args) {
boolean loop = true;
while (loop == true){
commands();
System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
String function = input.nextLine();
System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
double n1 = input.nextDouble();
input.nextLine();
System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
double n2 = input.nextDouble();
input.nextLine();
//=======================
// Addition
//=======================
if (function.equals("+")){
double sum = n1+n2;
System.out.println(n1+"+"+ n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
}
}
after every input.nextDouble(); you need to call input.nextLine(); to consume the new line, see Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
remove the unnecessary input.nextLine(); after every String command = input.nextLine();
The nextDouble() does not consume the new line. You can fix this by parsing the full line and then use Double.parseDouble() to get the double value from the line like this
....
System.out.println("Enter the first number to be"+
"calculated (If dividing, this is the numerator):");
double n1 = Double.parseDouble(input.nextLine());
System.out.println("Enter the second number to be" +
"calculated (If dividing, this is the denominator):");
double n2 = Double.parseDouble(input.nextLine());
if (function.equals("+")) {
double sum = n1 + n2;
System.out.println(n1 + "+" + n2 + " = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
switch (command) {
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
}
....
Note
You do not have to check while(loop == true) with boolean variables you can just do check by doing while(loop).
Check this Complete code link
There are few things you need to take care of.
Have a good exception handling.
Validate the user inputs
Changes I made to your code-
clear the placeHolder value in clear() method
using input.next() inplace of input.nextLine() and removing extra input.newLine() methods
added break statements to all switch statements
You need to modularize a lot of things in your code. Have a look at Best Coding practice
input.nextDouble() reads the numbers, but does nothing with the end-of-line. So when you do this later in the code:
String command = input.nextLine();
it handles the left-over end of line, not the "m" you type next.
To fix, do something to handle the end of line on your input, such as adding input.nextLine() after calling nextDouble():
double n1 = input.nextDouble();
input.nextLine();
double n2 = input.nextDouble();
input.nextLine();
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
String item1="Burger";
String item2="Softdrink";
int burger_price=40, sofdrink_price=20;
int x=0;
while(x==0){
System.out.println("Select item [1] burger [2] sofdrink");
int select=scan.nextInt();
switch(select){
case 1:
System.out.println("Enter Quantity: ");
int qty=scan.nextInt();
int total=qty*burger_price;
System.out.println("Item: Burger");
System.out.println("Quanity: "+qty);
System.out.println("Total: "+total);
x=1;
break;
case 2:
System.out.println("Enter Quantity: ");
int qty2=scan.nextInt();
int total2=qty2*sofdrink_price;
System.out.println("Item: Softdrink");
System.out.println("Quanity: "+qty2);
System.out.println("Total: "+total2);
x=1;
break;
default: System.out.println("Select [1] and [2] only");
}
}//end while`
MadProgrammer gave a really great explanation. I just put it together as a code. I tried to make minimum changes to your original code so that you understand better.
import java.util.Scanner;
public class BugerCheese {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int burger_price=40, sofdrink_price=20;
int qty1=0, qty2=0;
while(true){
System.out.println("Select item [1] burger [2] sofdrink");
int select=scan.nextInt();
switch(select){
case 1:
System.out.println("Enter Quantity: ");
qty1 += scan.nextInt();
break;
case 2:
System.out.println("Enter Quantity: ");
qty2 += scan.nextInt();
break;
default: System.out.println("Select [1] and [2] only");
}
System.out.println("Enter 9 to add more items. Enter any other key to calculate total");
if(9!=scan.nextInt()){
break;
}
}
if(qty1>0){
int total=qty1*burger_price;
System.out.println("Item: Burger");
System.out.println("Quanity: "+qty1);
System.out.println("Total: "+total);
}
if(qty2>0){
int total2=qty2*sofdrink_price;
System.out.println("Item: Softdrink");
System.out.println("Quanity: "+qty2);
System.out.println("Total: "+total2);
}
System.out.println("GrandTotal: "+(qty1*burger_price+qty2*sofdrink_price));
}
}
First, you need some kind of loop...
boolean done = false;
do {
//...
} while (!done);
Then you need to provide some way for the user to exit the loop
boolean done = false;
do {
System.out.println("Select item [1] burger [2] sofdrink or [0] when you're done");
//...
switch(select){
case 0:
done = true;
break;
}
} while (!done);
Now, you need someway to keep a running tally of what's been ordered, since you only have two items, you could use two variables...
int burgerCount = 0;
int softDrinkCount = 0;
boolean done = false;
do {
//...
Now you can just increment the counters based on the user selection...
Now, automatically, you need to ask the user for two things, what they want and how much they want, you could simplify the process a bit by been a little clever...
System.out.println("Select item [1] burger [2] sofdrink or [0] when you're done");
int select=scan.nextInt();
scan.nextLine();
switch (select) {
case 0:
done = true;
break;
case 1:
case 2:
System.out.println("Enter Quantity: ");
int qty=scan.nextInt();
scan.nextLine();
switch (select) {
case 1:
burgerCount += qty;
break;
case 1:
softDrinkCount += qty;
break;
}
break;
}
// Show details
Make sure, you call nextLine after you read the nextInt, as there is still a carriage return in the buffer ;)
Then you can display running a tally...
//...
System.out.println("You've ordered...");
double burgerTally = burger_price * burgerCount;
double drinkTally = burger_price * drinkTally;
System.out.println(burgerCount + " burgers # $" + burger_price + " for a sub total of $" + burgerTally);
System.out.println(softDrinkCount + " soft drinks # $" + sofdrink_price + " for a sub total of $" + drinkTally);
System.out.println("For a total of $" + (burgerTally + drinkTally));
} while (!done);
Because of the way the code is laid out, the tally will be displayed regardless of what you pick...
Now, if you have more items, then an array is going to come in very handy and will reduce the over all amount of code you might need...