Related
My final project for class is a text based game. So far I have it working how I want, except for 1 or 2 issues. First big issue is when I enter my "magic" menu (switch statement loop) none of the data has any impact. Meaning if the user's HP drops below 0, they don't die, it doesn't happen until you exit the loop. I've messed with it, and made it work, but it broke other parts of the code, so please help if you can.
Another solution I was able to do was setting the boolean value to false after each case, making the user enter a case, then it jumps out of the switch, which works great, except it executes the entire switch loop, meaning every single input.
Here's the main code, keep in mind it has another class
package textRPG;
import java.util.Random;
import java.util.Scanner;
public class LoopyLoop {
private static int maxEnemyHealth = 155;
private static int enemyAttackDmg = 25;
private static int health = 109;
private static int attackDmg = 30;
private static int mana = 15;
private static int numHealthPots = 3;
private static int healthPotionHealAmount = 30;
private static int healthPotionDropChance = 20;
private static int manaPotionRecoveryAmount = 12;
private static int count = 0;
private static int count2 = 0;
private static int expUp = 0;
private static int level = 1;
public static void main(String[] args) {
SpellsAndAbilities spells = new SpellsAndAbilities();
Scanner in = new Scanner(System.in);
Random rand = new Random();
//String Array for enemies, more can be added, or taken away
String[] enemies = {"Skeleton", "Zombie", "Goblin", "Tiny Dragon", "Ben Afleck", "Little weird man", "Huge Bee", "Jeff", "Crazy Ray"};
//Set a variable running to true, to allow the program to run, so that if the user chooses to end the game early, they can do so
boolean running = true;
System.out.println("==================================================================");
System.out.println("Welcome to Mysterical World of Mysterical Things!");
System.out.println("Please press the number corresponding the action you wish to take.");
System.out.println("==================================================================");
//Clause to keep the game running with invalid inputs
GAME:
while(running) {
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\n\t### " + enemy + " has appeared! ###\n");
while (enemyHealth > 0) {
System.out.println("\tYour HP: " + health);
System.out.println("\tYour Mana: " + mana);
System.out.println("\t" + enemy + "'s HP: " + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Spells");
System.out.println("\t3. Use potion");
System.out.println("\t4. Run");
String input = in.nextLine();
if (input.equals("1")) {
int damageDealt = rand.nextInt(attackDmg);
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t>>> You hit the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> The " + enemy + " hit you for " + damageTaken + " damage <<<");
System.out.println();
if(health < 1) {
System.out.println("\t=== You died! ===");
break;
}
//
//Problem Starts Here
//
}else if (input.equals("2")) {
boolean set=true;
while(set) {
System.out.println("____________________________________________\n");
System.out.println("1. Fireblast (Cost: 6 mana, Damage: 10-19)");
System.out.println("2. Ice Sickle (Cost: 9 mana, Damage: 22-26)");
System.out.println("3. Whirlwind (Cost: 14 mana, Damage: 31-36)");
System.out.println("4. Earth shard (Cost: 28 mana, Damage: 38-42)");
System.out.println("5. Heal (Cost: 50 mana, Heals: 35 to 55 HP)");
System.out.println("6. Exit this menu");
System.out.println("____________________________________________");
int spellInput = in.nextInt();
switch (spellInput) {
case 1: if(mana >= 6) {
mana -= 6;
int damageDealt = spells.fireBlast();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Fire Blast!");
System.out.println("\t====================");
System.out.println("\n\t>>> Fireblast hits the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " damage<<<");
System.out.println();
break;
}
else {
break;
}
case 2: if (mana >= 9) {
mana -= 9;
int damageDealt = spells.iceSickle();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Ice Sickle!");
System.out.println("\t====================");
System.out.println("\n\t>>> Ice Sickle slashes the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
System.out.println("You need more mana");
break;
}
case 3: if(mana >= 14) {
mana -= 14;
int damageDealt = spells.whirlWind();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Whirlwind!");
System.out.println("\t====================");
System.out.println("\n\t>>> Whirlwind ravages " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
break;
}
case 4: if(mana >= 28) {
mana -= 28;
int damageDealt = spells.earthShard();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Earth Shard!");
System.out.println("\t====================");
System.out.println("\n\t>>> Earth shard pummels " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
break;
}
case 5: if(mana >= 50) {
mana -= 50;
health += spells.Heal();
int damageTaken = rand.nextInt(enemyAttackDmg);
health -= damageTaken;
System.out.println("\t===============");
System.out.println("\tYou cast Heal!");
System.out.println("\t===============");
System.out.println("\n\t>>> You recover " + spells.Heal() + " HP <<<");
System.out.println("\t>>> You took " + damageTaken+ " damage <<<");
System.out.println("\tYour HP: " + health);
System.out.println("\tYour Mana: " + mana);
System.out.println();
break;
}
else {
break;;
}
case 6: set = false;
default: break;
}
}
}
else if (input.equals("3")) {
if (numHealthPots > 0) {
count2++;
health += healthPotionHealAmount;
mana += manaPotionRecoveryAmount;
numHealthPots--;
System.out.println("\tYou drink a potion, healing for " + healthPotionHealAmount + " HP and recovering " + manaPotionRecoveryAmount + " mana" +
"\n\t>> You now have " + health + " HP and " + mana +" Mana <<" +
"\n\t>> You have " + numHealthPots + " potions left <<");
}
else {
System.out.println("\tYou have no potions left! Defeat enemies for a chance to get one!");
}
} else if (input.equals("4")) {
System.out.println("\tYou run away from the " + enemy + "!");
continue GAME;
}
else {
System.out.println("-------------------------------------");
}
}
if(health < 1) {
System.out.println("You pitifully limp out of the dungeon, too weak to go on!");
break;
}
count++;
System.out.println("=========================================");
System.out.println(" *** " + enemy +" was defeated! ***");
System.out.println("### You have " + health + " HP ### \n### And " + mana + " mana ###");
expUp += expUp + 25;
if (rand.nextInt(100) < healthPotionDropChance) {
numHealthPots++;
System.out.println(" # The " + enemy + " dropped a health potion");
System.out.println(" # You now have " + numHealthPots + " health potion(s) # ");
}
if(expUp > 99) {
level++;
health = health+22;
attackDmg = attackDmg + 2;
mana = mana + 7;
System.out.println("****** LEVEL UP!!! ******");
System.out.println("You are now level " + level + "!");
System.out.println("Each level up rewards 22 to total health, +2 to attack, and +7 to mana!");
}
System.out.println("=========================================");
System.out.println("What would you like to do now?");
System.out.println("Press 1 to continue fighting");
System.out.println("Pess 2 to exit");
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command");
input = in.nextLine();
}
if (input.equals("1")) {
System.out.println("You choose to continue, good luck!");
}
else if (input.equals("2")) {
System.out.println("You exit the game");
break;
}
}
System.out.println("####################");
System.out.println("Thanks for playing!");
System.out.println("####################");
System.out.println("Press 5 to see your score!");
String input2 = in.nextLine();
if (input2.equals("5")){
System.out.println("You defeated " + count + " enemies");
System.out.println("Max level achieved: " + level);
System.out.println("And you used " + count2 + " potions");
}
else {
System.out.println("Invalid input");
input2 = in.nextLine();
}
in.close();
}
}
Output ends up looking like this:
6. Exit this menu
____________________________________________
6
=========================================
*** Tiny Dragon was defeated! ***
### You have 136 HP ###
### And 6 mana ###
****** LEVEL UP!!! ******
I am just 2 months into programming so I apologize for my poorly written code. I appreciate it if you will give me tips and advice on how i can improve my code.
I created a program that creates a hero.(in this case I used dota heroes)
The program starts by asking The hero name, Health pool, mana pool, attack speed and attack damage.
after I created a method that will ask a user what type of hero it is.
the selection are 1. Strength 2. Agility 3. Intelligence. Each selection will set the hero's attack damage per level, attack speed per level, Hp per level and mp per level.
after this, the program will then ask a user to choose a level(max level is only 25)
after selecting the level the program will display the new attributes after leveling up. for example if the user chooses 25 then Healthpool = healthpool + (hp per level * selected level) and etc.
After this the program will then show a selection of enemies in this example is tower and roshan.
after the user chooses an enemy the program will then show an option on what to do such as 1. attack 2. end.
What I want to happen is when the user chooses to attack, I want the program to show the current hp of the tower after attacking then will go back to the options on what to do.
I really do not know what loop should I do.
import java.util.Scanner;
class Hero {
Scanner sc = new Scanner(System.in);
String name, heroType, heroOpponent;
double baseHp, baseMp, baseAs, baseAd, asplvl, adplvl, hplvl, mplvl, tower;
int lvl, type, opponent, option;
void UserInput() {
System.out.print("Please enter hero name: ");
name = sc.nextLine();
System.out.print("Please enter your base Health Pool: ");
baseHp = sc.nextDouble();
System.out.print("Please enter your base Mana Pool: ");
baseMp = sc.nextDouble();
System.out.print("Please enter your base Attack Speed: ");
baseAs = sc.nextDouble();
System.out.print("Please enter your base Attack Damage: ");
baseAd = sc.nextDouble();
}
void TypeMethod() {
do {
System.out.println("Please select your hero type");
System.out.println();
System.out.println("1. Strength");
System.out.println("2. Agility");
System.out.println("3. Intelligence");
type = sc.nextInt();
switch (type) {
case 1:
heroType = ("Strength");
asplvl = 2.5;
adplvl = 5;
hplvl = 20;
mplvl = 12;
break;
case 2:
heroType = ("Agility");
asplvl = 7;
adplvl = 5;
hplvl = 12;
mplvl = 12;
break;
case 3:
heroType = ("Intelligence");
asplvl = 2.5;
adplvl = 5;
hplvl = 12;
mplvl = 20;
break;
default:
System.out.println("Selection Error! Try again!");
}
} while (type > 3 && type < 1);
}
void DisplayUserInput() {
System.out.println("Hero name: " + name);
System.out.println("Hero type: " + heroType);
System.out.println("Base Health Pool: " + baseHp);
System.out.println("Base Mana Pool: " + baseMp);
System.out.println("Base Attack Speed: " + baseAs);
System.out.println("Base Attack Damage: " + baseAd);
}
int HeroLevel() {
do {
System.out.println("Choose your level! Maximum level is 25");
lvl = sc.nextInt();
return lvl;
} while (lvl > 25 | lvl < 0);
}
double MpAfterLevel(int i) {
return baseMp = baseMp + (mplvl * (double) i);
}
double HpAfterLevel(int i) {
return baseHp + (hplvl * (double) i);
}
double AsAfterLevel(int i) {
return baseAs = baseAs + (baseAs * (double) i);
}
double AdAfterLevel(int i) {
return baseAd = baseAd + (baseAd * (double) i);
}
void DisplayHeroAfterLevel() {
System.out.println("Hero name : " + name);
System.out.println("Hero type : " + heroType);
System.out.println("Health Pool after at level " + lvl + " " + baseHp);
System.out.println("Mana Pool after at level " + lvl + " " + baseMp);
System.out.println("Attack Damage after at level " + lvl + " " + baseAd);
System.out.println("Attack Speed after at level " + lvl + " " + baseAs);
System.out.println();
}
void WhotoAttack() {
System.out.println("Please select an opponent");
System.out.println("1. Tower");
System.out.println("2. Roshan");
opponent = sc.nextInt();
switch (opponent) {
case 1:
do {
tower = 5000;
System.out.println("tower has " + tower + " Health points");
System.out.println("Please take action!");
System.out.println("1. Attack ");
System.out.println("2. End");
option = sc.nextInt();
switch (option) {
case 1:
case 2:
}
} while (tower != 0);
}
}
}
public class DotaHeroV1 {
public static void main(String args[]) {
Hero h1 = new Hero();
int i;
h1.UserInput();
h1.TypeMethod();
h1.DisplayUserInput();
i = h1.HeroLevel();
h1.HpAfterLevel(i);
h1.MpAfterLevel(i);
h1.AsAfterLevel(i);
h1.AdAfterLevel(i);
h1.DisplayHeroAfterLevel();
h1.WhotoAttack();
}
}
It's been more than a year, and I've just stumbled onto this question.
You probably don't need an answer anymore, but if you happen to need it i am making a game that involves enemies attacking each other until someone dies.
Here's a snippet for what I'm using for a Player1 attacking a Player2:
new Thread(new Runnable() {
#Override
public void run() {
do {
try {
System.out.println("DELAYING " + (long) game.getAttackDelay(finalPlayer1));
Thread.sleep((long) game.getAttackDelay(finalPlayer1));
float p1DamageDealt = game.fight(finalPlayer1, finalPlayer2);
game.setCurrentHp(finalPlayer2, p1DamageDealt);
if (game.getCurrentHp(finalPlayer1) <= 0 || game.getCurrentHp(finalPlayer2) <= 0) {
break;
}
sendToPlayerOne.writeObject("YOU DEALT " + p1DamageDealt + "!");
sendToPlayerTwo.writeObject("YOU TOOK " + p1DamageDealt + "!");
sendToPlayerOne.writeObject("ENEMY HAS " + game.getCurrentHp(finalPlayer2) + " HP LEFT!");
sendToPlayerTwo.writeObject("YOU HAVE " + game.getCurrentHp(finalPlayer2) + " HP LEFT!");
//sendToPlayerOne.writeObject(p1DamageDealt);
} catch (InterruptedException | IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
} while (finalPlayer1.getCurrentHp() > 0 && finalPlayer2.getCurrentHp() > 0);
if (finalPlayer1.getCurrentHp() <= 0 && finalPlayer2.getCurrentHp() > 0) {
gameResult = "YOU LOSE!";
} else if (finalPlayer2.getCurrentHp() <= 0 && finalPlayer1.getCurrentHp() > 0) {
gameResult = "YOU WIN!";
} else {
gameResult = "IT'S A TIE!\n"
+ "Your HP : " + finalPlayer1.getCurrentHp() + "\n"
+ "Enemy HP:" + finalPlayer2.getCurrentHp();
}
try {
sendToPlayerOne.writeObject(gameResult);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
It's not very good but works for what I need, and probably will work for you with some adjustments, since the basics for this to work is just do a "do X(attack) while Y(enemy health is not 0)"
i have a cashiering system and here's my codes:
import javax.swing.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FinalProject {
private static final int totalsundae = 0;
public static void main(String[] args) {
int totaldrinks = 0, totalfries = 0, totalburger = 0, totalsundae = 0;
FinalProject m = new FinalProject();
m.Cashiering();
}
public void Cashiering() {
String menu[] = {"Customer's Name", "Menu", "Pay", "View Order list", "Exit"};
String choice = "";
char ch;
do {
choice = (String) JOptionPane.showInputDialog(null, "Please select your order", "menu", 1, null, menu, menu[0]);
ch = choice.toLowerCase().charAt(0);
switch (ch) {
case 'c':
customer();
break;
case 'm':
menu2();
break;
case 'p':
getTotal();
break;
case 'v':
orderList();
break;
case 'e':
System.exit(0);
}
} while (!choice.equals("Close"));
}
public void customer() {
String name = (String) JOptionPane.showInputDialog("WELCOME !!!!! \n\nPLEASE ENTER YOUR NAME: ");
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt", true));
printW.println("Customer's Name " + "\n" + name);
JOptionPane.showMessageDialog(null, "Your Name successfully stored \n\n You can Order Now ");
printW.close();
} catch (Exception e) {
}
}
public int burger() {
int burger = 0, quantity = 0, totalburger = 0;
int choice;
String burgnm = "";
String menu = "\nBURGER: \n1.Regular Burger 45 \n2.Burger with cheese---->55 \n3.Burger with egg and cheese----50 \n4.Burger with ham---->60 \n5.Burger with ham and cheese---->70 ";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: " + menu));
switch (choice) {
case 1:
burger += 45;
burgnm = "Regular Burger - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 2:
burger += 55;
burgnm = "Burger with cheese - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 3:
burger += 50;
burgnm = "Burger with egg and cheese - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 4:
burger += 60;
burgnm = "Burger with ham - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 5:
burger += 70;
burgnm = "Burger with ham and cheese - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalburger = quantity * burger;
burgnm = burgnm + totalburger + "\n";
JOptionPane.showMessageDialog(null, "Total = " + burgnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt", true));
if (choice == 1) {
printW.println("Customer's Order " + "\n" + quantity + burgnm);
} else if (choice == 2)
printW.println("Customer's Order " + "\n" + quantity + burgnm);
else if (choice == 3)
printW.println("Customer's Order " + "\n" + quantity + burgnm);
else if (choice == 4)
printW.println("Customer's Order " + "\n" + quantity + burgnm);
else if (choice == 5)
printW.println("Customer's Order " + "\n" + quantity + burgnm);
JOptionPane.showMessageDialog(null, "Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
return totalburger;
}
public int Spaghetti() {
int choice, quantity = 0, totalspag = 0, spaghetti = 0;
String spagnm = null;
String menu = "\nSPAGHETTI: \n1.Regular spaghetti---->60 \n2.Large Spaghetti---->70";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: " + menu));
switch (choice) {
case 1:
spaghetti += 60;
spagnm = "Regular Spaghetti - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 2:
spaghetti += 70;
spagnm = "Large Spaghetti - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalspag = quantity * spaghetti;
spagnm = spagnm + totalspag + "\n";
JOptionPane.showMessageDialog(null, "Total = " + spagnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt", true));
if (choice == 1) {
printW.println("Customer's Order " + "\n" + quantity + spagnm);
} else if (choice == 2)
printW.println("Customer's Order " + "\n" + quantity + spagnm);
JOptionPane.showMessageDialog(null, "Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
return totalspag;
}
public int Fries() {
int choice, fries = 0, quantity = 0, totalfries = 0;
String friesnm = "";
String menu = "\nFRIES: \n1.Regular Fries ----> 35\n2.Medium Fries ----> 45 \n3.LargeFries ----> 55";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: " + menu));
switch (choice) {
case 1:
fries += 35;
friesnm = "Regular Fries - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 2:
fries += 45;
friesnm = "Medium Fries - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 3:
fries += 55;
friesnm = "Large Fries - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalfries = quantity * fries;
friesnm = friesnm + totalfries + "\n";
JOptionPane.showMessageDialog(null, "Total = " + friesnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt", true));
if (choice == 1) {
printW.println("Customer's Order " + "\n" + quantity + friesnm);
} else if (choice == 2)
printW.println("Customer's Order " + "\n" + quantity + friesnm);
else if (choice == 3)
printW.println("Customer's Order " + "\n" + quantity + friesnm);
JOptionPane.showMessageDialog(null, "Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
return totalfries;
}
public int Sundae() {
int choice, quantity = 0, sundae = 0, totalsun = 0;
String sundaenm = "";
String menu = "\nSUNDAE: \n1.Choco sundae ----> 28 \n2.Caramel sundae ----> 28 \n3.Strawberry sundae ----> 28";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: " + menu));
switch (choice) {
case 1:
sundae += 28;
sundaenm = " Choco Sundae -";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 2:
sundae += 28;
sundaenm = " Caramel Sundae ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 3:
sundae += 28;
sundaenm = " Strawberry Sundae - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalsun = quantity * sundae;
sundaenm = sundaenm + totalsun + "\n";
JOptionPane.showMessageDialog(null, "Total = " + sundaenm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt", true));
if (choice == 1) {
printW.println("Costumer's Order " + "\n" + quantity + sundaenm);
} else if (choice == 2)
printW.println("Costumer's Order " + "\n" + quantity + sundaenm);
else if (choice == 3)
printW.println("Costumer's Order " + "\n" + quantity + sundaenm);
JOptionPane.showMessageDialog(null, "Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
return totalsun;
}
public int Drinks() {
int choice, quantity = 0, drinks = 0, totaldrinks = 0;
String drinksnm = "";
String menu = "\nDRINKS: \n1.Reg. Coke ----> 25 \n2.Large Coke ----> 35 \n3.Reg.Sprite ----> 28 \n4.Large Sprite ----> 38";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: " + menu));
switch (choice) {
case 1:
drinks += 25;
drinksnm = "Regular Coke - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 2:
drinks += 35;
drinksnm = "Large Coke - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 3:
drinks += 28;
drinksnm = "Regular Sprite - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
case 4:
drinksnm = "Large Sprite - ";
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totaldrinks = quantity * drinks;
drinksnm = drinksnm + totaldrinks + "\n";
JOptionPane.showMessageDialog(null, "Total = " + drinksnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt", true));
if (choice == 1) {
printW.println("Costumer's Order " + "\n" + quantity + drinksnm);
} else if (choice == 2)
printW.println("Costumer's Order " + "\n" + quantity + drinksnm);
else if (choice == 3)
printW.println("Costumer's Order " + "\n" + quantity + drinksnm);
else if (choice == 4)
printW.println("Costumer's Order " + "\n" + quantity + drinksnm);
JOptionPane.showMessageDialog(null, "Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
return totaldrinks;
}
public void orderList() {
try {
Scanner in = new Scanner(new FileReader("cash.txt"));
String all = "\nWELCOME !!!! \nCASHIERING SYSTEM\n";
while (in.hasNext()) {
all = all + in.nextLine() + "\n";
}
JOptionPane.showMessageDialog(null, new JTextArea(all));
in.close();
} catch (Exception e) {
}
}
public void getTotal() {
}
public void menu2() {
String menu[] = {"Burger", "Spaghetti", "Fries", "Ice Sundae", "Drinks", "Exit"};
String choice = "";
char ch;
int yesorno = 0;
do {
choice = (String) JOptionPane.showInputDialog(null, "Please select your order", "menu", 1, null, menu, menu[0]);
ch = choice.toLowerCase().charAt(0);
switch (ch) {
case 'b':
burger();
yesorno = Integer.parseInt(JOptionPane.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 's':
Spaghetti();
yesorno = Integer.parseInt(JOptionPane.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'f':
Fries();
yesorno = Integer.parseInt(JOptionPane.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'i':
Sundae();
yesorno = Integer.parseInt(JOptionPane.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'd':
Drinks();
yesorno = Integer.parseInt(JOptionPane.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'e':
break;
}
} while (!choice.equals("Close"));
}
}
my problem here is the total. how can i get the total of the customer's order by using a method? i'm really a beginner in java so i hope you can give some simple codes. thank you so much for your help!
Use a totalOrder variable to store the total for that session.
import javax.swing.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FinalProject {
private int totalOrder;
private static final int totalsundae = 0;
public static void main(String[] args) {
int totaldrinks = 0, totalfries = 0, totalburger = 0, totalsundae = 0;
FinalProject m = new FinalProject();
m.Cashiering();
}
public void Cashiering() {
String menu[] = { "Customer's Name", "Menu", "Pay", "View Order list",
"Exit" };
String choice = "";
char ch;
do {
choice = (String) JOptionPane.showInputDialog(null,
"Please select your order", "menu", 1, null, menu, menu[0]);
ch = choice.toLowerCase().charAt(0);
switch (ch) {
case 'c':
customer();
break;
case 'm':
menu2();
break;
case 'p':
getTotal();
break;
case 'v':
orderList();
break;
case 'e':
System.exit(0);
}
} while (!choice.equals("Close"));
}
public void customer() {
String name = (String) JOptionPane
.showInputDialog("WELCOME !!!!! \n\nPLEASE ENTER YOUR NAME: ");
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt",
true));
printW.println("Customer's Name " + "\n" + name);
JOptionPane.showMessageDialog(null,
"Your Name successfully stored \n\n You can Order Now ");
printW.close();
} catch (Exception e) {
}
}
public int burger() {
int burger = 0, quantity = 0, totalburger = 0;
int choice;
String burgnm = "";
String menu = "\nBURGER: \n1.Regular Burger 45 \n2.Burger with cheese---->55 \n3.Burger with egg and cheese----50 \n4.Burger with ham---->60 \n5.Burger with ham and cheese---->70 ";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: "
+ menu));
switch (choice) {
case 1:
burger += 45;
burgnm = "Regular Burger - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 2:
burger += 55;
burgnm = "Burger with cheese - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 3:
burger += 50;
burgnm = "Burger with egg and cheese - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 4:
burger += 60;
burgnm = "Burger with ham - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 5:
burger += 70;
burgnm = "Burger with ham and cheese - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalburger = quantity * burger;
burgnm = burgnm + totalburger + "\n";
JOptionPane.showMessageDialog(null, "Total = " + burgnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt",
true));
if (choice == 1) {
printW.println("Customer's Order " + "\n" + quantity
+ burgnm);
} else if (choice == 2)
printW.println("Customer's Order " + "\n" + quantity
+ burgnm);
else if (choice == 3)
printW.println("Customer's Order " + "\n" + quantity
+ burgnm);
else if (choice == 4)
printW.println("Customer's Order " + "\n" + quantity
+ burgnm);
else if (choice == 5)
printW.println("Customer's Order " + "\n" + quantity
+ burgnm);
JOptionPane.showMessageDialog(null,
"Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
totalOrder = totalOrder + totalburger;
return totalburger;
}
public int Spaghetti() {
int choice, quantity = 0, totalspag = 0, spaghetti = 0;
String spagnm = null;
String menu = "\nSPAGHETTI: \n1.Regular spaghetti---->60 \n2.Large Spaghetti---->70";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: "
+ menu));
switch (choice) {
case 1:
spaghetti += 60;
spagnm = "Regular Spaghetti - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 2:
spaghetti += 70;
spagnm = "Large Spaghetti - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalspag = quantity * spaghetti;
spagnm = spagnm + totalspag + "\n";
JOptionPane.showMessageDialog(null, "Total = " + spagnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt",
true));
if (choice == 1) {
printW.println("Customer's Order " + "\n" + quantity
+ spagnm);
} else if (choice == 2)
printW.println("Customer's Order " + "\n" + quantity
+ spagnm);
JOptionPane.showMessageDialog(null,
"Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
totalOrder = totalOrder + totalspag;
return totalspag;
}
public int Fries() {
int choice, fries = 0, quantity = 0, totalfries = 0;
String friesnm = "";
String menu = "\nFRIES: \n1.Regular Fries ----> 35\n2.Medium Fries ----> 45 \n3.LargeFries ----> 55";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: "
+ menu));
switch (choice) {
case 1:
fries += 35;
friesnm = "Regular Fries - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 2:
fries += 45;
friesnm = "Medium Fries - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 3:
fries += 55;
friesnm = "Large Fries - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalfries = quantity * fries;
friesnm = friesnm + totalfries + "\n";
JOptionPane.showMessageDialog(null, "Total = " + friesnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt",
true));
if (choice == 1) {
printW.println("Customer's Order " + "\n" + quantity
+ friesnm);
} else if (choice == 2)
printW.println("Customer's Order " + "\n" + quantity
+ friesnm);
else if (choice == 3)
printW.println("Customer's Order " + "\n" + quantity
+ friesnm);
JOptionPane.showMessageDialog(null,
"Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
totalOrder = totalOrder + totalfries;
return totalfries;
}
public int Sundae() {
int choice, quantity = 0, sundae = 0, totalsun = 0;
String sundaenm = "";
String menu = "\nSUNDAE: \n1.Choco sundae ----> 28 \n2.Caramel sundae ----> 28 \n3.Strawberry sundae ----> 28";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: "
+ menu));
switch (choice) {
case 1:
sundae += 28;
sundaenm = " Choco Sundae -";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 2:
sundae += 28;
sundaenm = " Caramel Sundae ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 3:
sundae += 28;
sundaenm = " Strawberry Sundae - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totalsun = quantity * sundae;
sundaenm = sundaenm + totalsun + "\n";
JOptionPane.showMessageDialog(null, "Total = " + sundaenm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt",
true));
if (choice == 1) {
printW.println("Costumer's Order " + "\n" + quantity
+ sundaenm);
} else if (choice == 2)
printW.println("Costumer's Order " + "\n" + quantity
+ sundaenm);
else if (choice == 3)
printW.println("Costumer's Order " + "\n" + quantity
+ sundaenm);
JOptionPane.showMessageDialog(null,
"Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
totalOrder = totalOrder + totalsun;
return totalsun;
}
public int Drinks() {
int choice, quantity = 0, drinks = 0, totaldrinks = 0;
String drinksnm = "";
String menu = "\nDRINKS: \n1.Reg. Coke ----> 25 \n2.Large Coke ----> 35 \n3.Reg.Sprite ----> 28 \n4.Large Sprite ----> 38";
choice = Integer.parseInt(JOptionPane.showInputDialog("Please select: "
+ menu));
switch (choice) {
case 1:
drinks += 25;
drinksnm = "Regular Coke - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 2:
drinks += 35;
drinksnm = "Large Coke - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 3:
drinks += 28;
drinksnm = "Regular Sprite - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
case 4:
drinksnm = "Large Sprite - ";
quantity = Integer.parseInt(JOptionPane
.showInputDialog("How many do you want??? "));
break;
default:
JOptionPane.showMessageDialog(null, "INVALID");
}
if (quantity < 0) {
JOptionPane.showMessageDialog(null, "INVALID");
} else {
totaldrinks = quantity * drinks;
drinksnm = drinksnm + totaldrinks + "\n";
JOptionPane.showMessageDialog(null, "Total = " + drinksnm);
try {
PrintWriter printW = new PrintWriter(new FileWriter("cash.txt",
true));
if (choice == 1) {
printW.println("Costumer's Order " + "\n" + quantity
+ drinksnm);
} else if (choice == 2)
printW.println("Costumer's Order " + "\n" + quantity
+ drinksnm);
else if (choice == 3)
printW.println("Costumer's Order " + "\n" + quantity
+ drinksnm);
else if (choice == 4)
printW.println("Costumer's Order " + "\n" + quantity
+ drinksnm);
JOptionPane.showMessageDialog(null,
"Record successfully stored ");
printW.close();
} catch (Exception e) {
}
}
totalOrder = totalOrder + totaldrinks;
return totaldrinks;
}
public void orderList() {
try {
Scanner in = new Scanner(new FileReader("cash.txt"));
String all = "\nWELCOME !!!! \nCASHIERING SYSTEM\n";
while (in.hasNext()) {
all = all + in.nextLine() + "\n";
}
JOptionPane.showMessageDialog(null, new JTextArea(all));
in.close();
} catch (Exception e) {
}
}
public void getTotal() {
JOptionPane.showMessageDialog(null, "Order Total\n"+ totalOrder + "");
}
public void menu2() {
String menu[] = { "Burger", "Spaghetti", "Fries", "Ice Sundae",
"Drinks", "Exit" };
String choice = "";
char ch;
int yesorno = 0;
do {
choice = (String) JOptionPane.showInputDialog(null,
"Please select your order", "menu", 1, null, menu, menu[0]);
ch = choice.toLowerCase().charAt(0);
switch (ch) {
case 'b':
burger();
yesorno = Integer
.parseInt(JOptionPane
.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 's':
Spaghetti();
yesorno = Integer
.parseInt(JOptionPane
.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'f':
Fries();
yesorno = Integer
.parseInt(JOptionPane
.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'i':
Sundae();
yesorno = Integer
.parseInt(JOptionPane
.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'd':
Drinks();
yesorno = Integer
.parseInt(JOptionPane
.showInputDialog("Do you still have any order?? \n 1.Yes \n2.No"));
if (yesorno == 1) {
menu2();
} else {
Cashiering();
}
break;
case 'e':
break;
}
} while (!choice.equals("Close"));
}
}
I have a POS program that is not working it says switch(food) unreachable statement
import javax.swing.*;
import java.awt.*;
public class sari{
public static void One()
{
int choice=0,food=0,c=0,con,x=1,y=1,z=1,q=1,trans=0,price=0 ,qty,gtotal=0,ptotal=0,pay,change,total=0,ord;
String order="",bibilhin="",transaction="",A;
ImageIcon welcome = new ImageIcon("welcome.jpg");
ImageIcon chip = new ImageIcon("chip.jpg");
ImageIcon rc = new ImageIcon("rc.jpg");
ImageIcon stick = new ImageIcon("stick.jpg");
ImageIcon pancit = new ImageIcon("pancit.jpg");
ImageIcon jampong = new ImageIcon("jampong.jpg");
ImageIcon chups = new ImageIcon("chups.jpg");
ImageIcon egg = new ImageIcon("egg.jpg");
A=JOptionPane.showInputDialog("Enter your name:"); ImageIcon hansel = new ImageIcon("hansel.jpg");
JOptionPane.showMessageDialog(null,"Sir/Ma`am \n "+A+"\n Welcome\n to Mang Inasal\n Please Choose The\n product you want to buy","Welcome" ,JOptionPane.PLAIN_MESSAGE,welcome);
while(x==1)
{
c=Integer.parseInt(JOptionPane.showInputDialog(" Categories" + "\n" +"[1] Drinks" + "\n" + "[2] Foods"));
if(c==1)
{choice=Integer.parseInt(JOptionPane.showInputDialog("DRINKS" +"\n"
+ "[1] Lemonade" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
if(c==2)
food=Integer.parseInt(JOptionPane.showInputDialog("Food" +"\n"
+ "[1] L" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
}
switch(choice)
{
case 1:
price = 20;
bibilhin= " Lemonade";
break;
case 2:
price = 20;
bibilhin= "Coca Cola ";
break;
case 3:
price =820;
bibilhin = "Sprite";
break;
case 4:
price =205;
bibilhin= "Mountain dew";
break;
case 5:
price =20;
bibilhin= "Pepsi";
break;
case 6:
price =25;
bibilhin= "Cofee ";
break;
case 7:
price =25;
bibilhin= "Hot Choco";
break;
case 8:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 9:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
break;
switch(food)
{
case 11:
price = 20;
bibilhin= " Lemonade";
break;
case 12:
price = 20;
bibilhin= "Coca Cola ";
break;
case 13:
price =820;
bibilhin = "Sprite";
break;
case 14:
price =205;
bibilhin= "Mountain dew";
break;
case 15:
price =20;
bibilhin= "Pepsi";
break;
case 16:
price =25;
bibilhin= "Cofee ";
break;
case 17:
price =25;
bibilhin= "Hot Choco";
break;
case 18:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 19:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
continue;
}
}
}
You have an unconditional break right before the switch in question.
As an aside, I think this is the perfect time to learn about functions and how to use them to make code more modular.
comment the break statement
import javax.swing.;
import java.awt.;
public class Test{
public static void main(String[] args)
{
int choice=0,food=0,c=0,con,x=1,y=1,z=1,q=1,trans=0,price=0 ,qty,gtotal=0,ptotal=0,pay,change,total=0,ord;
String order="",bibilhin="",transaction="",A;
ImageIcon welcome = new ImageIcon("welcome.jpg");
ImageIcon chip = new ImageIcon("chip.jpg");
ImageIcon rc = new ImageIcon("rc.jpg");
ImageIcon stick = new ImageIcon("stick.jpg");
ImageIcon pancit = new ImageIcon("pancit.jpg");
ImageIcon jampong = new ImageIcon("jampong.jpg");
ImageIcon chups = new ImageIcon("chups.jpg");
ImageIcon egg = new ImageIcon("egg.jpg");
A=JOptionPane.showInputDialog("Enter your name:"); ImageIcon hansel = new ImageIcon("hansel.jpg");
JOptionPane.showMessageDialog(null,"Sir/Ma`am \n "+A+"\n Welcome\n to Mang Inasal\n Please Choose The\n product you want to buy","Welcome" ,JOptionPane.PLAIN_MESSAGE,welcome);
while(x==1)
{
c=Integer.parseInt(JOptionPane.showInputDialog(" Categories" + "\n" +"[1] Drinks" + "\n" + "[2] Foods"));
if(c==1)
{choice=Integer.parseInt(JOptionPane.showInputDialog("DRINKS" +"\n"
+ "[1] Lemonade" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
if(c==2)
food=Integer.parseInt(JOptionPane.showInputDialog("Food" +"\n"
+ "[1] L" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
}
switch(choice)
{
case 1:
price = 20;
bibilhin= " Lemonade";
break;
case 2:
price = 20;
bibilhin= "Coca Cola ";
break;
case 3:
price =820;
bibilhin = "Sprite";
break;
case 4:
price =205;
bibilhin= "Mountain dew";
break;
case 5:
price =20;
bibilhin= "Pepsi";
break;
case 6:
price =25;
bibilhin= "Cofee ";
break;
case 7:
price =25;
bibilhin= "Hot Choco";
break;
case 8:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 9:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
// break;
switch(food)
{
case 11:
price = 20;
bibilhin= " Lemonade";
break;
case 12:
price = 20;
bibilhin= "Coca Cola ";
break;
case 13:
price =820;
bibilhin = "Sprite";
break;
case 14:
price =205;
bibilhin= "Mountain dew";
break;
case 15:
price =20;
bibilhin= "Pepsi";
break;
case 16:
price =25;
bibilhin= "Cofee ";
break;
case 17:
price =25;
bibilhin= "Hot Choco";
break;
case 18:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 19:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
continue;
}
}
}
I'm a beginner, so this result I am getting for one condition of my if else statement is blowing my mind. Everything works properly except for the condition when the QtyCalc variable is >= 100. The Finprice variable is listed as the disc variable and I can't figure out why. Help?
import javax.swing.JOptionPane;
public class SoftwareSales {
public static void main(String[] args) {
final int price = 99;
String Qty;
double QtyCalc, preprice, Finprice, disc;
Qty = JOptionPane.showInputDialog(null, "How many packages will you buy?");
QtyCalc = Double.parseDouble(Qty);
preprice = QtyCalc * price;
if (QtyCalc >= 100) {
disc = (preprice * (0.5));
Finprice = (preprice - disc);
JOptionPane.showMessageDialog(null, "Your discount is: " + disc + ".\n" + "Your final price is: " + Finprice + ". ");
} else if (QtyCalc >= 50 && QtyCalc <= 99) {
disc = (preprice * 0.4);
Finprice = (preprice - disc);
JOptionPane.showMessageDialog(null, "Your discount is: " + disc + ".\n" + "Your final price is: " + Finprice + ". ");
} else if (QtyCalc >= 20 && QtyCalc <= 49) {
disc = (preprice * 0.3);
Finprice = (preprice - disc);
JOptionPane.showMessageDialog(null, "Your discount is: " + disc + ".\n" + "Your final price is: " + Finprice + ". ");
} else if (QtyCalc >= 10 && QtyCalc <= 19) {
disc = (preprice * 0.2);
Finprice = (preprice - disc);
JOptionPane.showMessageDialog(null, "Your discount is: " + disc + ".\n" + "Your final price is: " + Finprice + ". ");
} else if (QtyCalc < 10 && QtyCalc >= 1) {
disc = 0;
Finprice = 0;
JOptionPane.showMessageDialog(null, "Sorry, there is no discount for purchases less than 10." + " Your price is: " + preprice);
} else {
JOptionPane.showMessageDialog(null, "You have entered an invalid number.");
}
disc = 0;
Finprice = 0;
System.exit(0);
}
}
The final price is equal to the discount when the quantity is >= 100 because the discount is 50% ... look at the code that you posted. In particular:
if (QtyCalc >= 100) {
disc = (preprice * (0.5));
Finprice = (preprice - disc);
JOptionPane.showMessageDialog(null, "Your discount is: " + disc + ".\n" + "Your final price is: " + Finprice + ". ");
}
There is no strange behavior, just simple math:
disc = (preprice * (0.5));
Finprice = (preprice - disc);
you should also consider eliminating redundant code:
import javax.swing.JOptionPane;
public class SoftwareSales {
public static void main(String[] args) {
final int PRICE = 99;
String qty;
double qtyCalc, preprice, finprice, disc;
disc = 0;
qtyCalc = 0;
boolean invalid = false;
do{
invalid = false;
qty = JOptionPane.showInputDialog(null, "How many packages will you buy?");
if (qty == null){
return;
}
try{
qtyCalc = Double.parseDouble(qty);
}catch(NumberFormatException e){
invalid = true;
}
}while(invalid);
preprice = qtyCalc * PRICE;
if (qtyCalc >= 100) {
disc = (preprice * (0.5));
} else if (qtyCalc >= 50 && qtyCalc <= 99) {
disc = (preprice * 0.4);
} else if (qtyCalc >= 20 && qtyCalc <= 49) {
disc = (preprice * 0.3);
} else if (qtyCalc >= 10 && qtyCalc <= 19) {
disc = (preprice * 0.2);
} else if (qtyCalc < 10 && qtyCalc >= 1) {
disc = 0;
finprice = 0;
JOptionPane.showMessageDialog(null, "Sorry, there is no discount for purchases less than 10. Your price is: " + preprice);
return;
} else {
JOptionPane.showMessageDialog(null, "You have entered an invalid number.");
return;
}
finprice = (preprice - disc);
JOptionPane.showMessageDialog(null, String.format("Your discount is: %.2f.\nYour final price is: %.2f. ",disc,finprice));
}
}
Also remember the java-convention for variables: always begin with lower-case.
finals alsways IN UPPER-CASE