This question already has answers here:
Unable to get total amount
(2 answers)
Closed 4 years ago.
I have designed a program which will rerun when the user enters "y" when asked if they wish to continue. The problem I am having is once the user enters "n" the program is supposed to display the total amount payable from all ticket options purchased. I have spent a couple of weeks stuck on this problem and am unsure of what to do next. I have only included the bottom part of my code. I have also included a photo to show my problem when the program is run.
here is my code:
package cse1pgx_a2;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int option, quantity, confirm;
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0;
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
Scanner input = new Scanner(System.in);
while (continueLoop) {
System.out.println("\t"+ "##### Welcome to Zoos Victoria #####");
System.out.println("\t" + "\t" + "MAIN MENU" + "\n");
System.out.println("\t" + "Zoo has the following ticketing options" + "\n");
System.out.println("\t" + "1 = Child (4-6 yrs)");
System.out.println("\t" + "2 = Adult (16+ yrs)");
System.out.println("\t" + "3 = Senior (60+ yrs)" + "\n");
System.out.println("Enter your option:" );
option=input.nextInt();
switch (option) {
case 1:
System.out.println("Enter total No of tickets for Child:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
case 2:
System.out.println("Enter total No of tickets for Adult:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
default:
System.out.println("Enter total No of tickets for Senior:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
}
if (confirm !=1) {
System.out.println("Incorrect key!");
}
OUTER:
while (confirm == 1) {
switch (option) {
case 1:
childTotal=(int) ((double) quantity*childCost) ;
System.out.println("Total amount for child tickets: $" + childTotal);
break OUTER;
case 2:
adultTotal=(int) ((double) quantity*adultCost) ;
System.out.println("Total amount for adult tickets $" + adultTotal);
break OUTER;
default:
seniorTotal=(int) ((double) quantity*seniorCost);
System.out.println("Total amount for senior tickets $" + seniorTotal);
break OUTER;
}
}
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
} else {
continueLoop = false;
switch (option) {
case 1:
finalTotal=(float) ((double) childTotal+adultTotal+seniorTotal) ;
System.out.println("Total amount payable: $ " + finalTotal);
break;
default:
System.out.println("Error");
}
}
}
}
}
I have fixed issues and also updated code for better performance.
package test;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final float childCost = 18;
final float adultCost = 36;
final float seniorCost = 32.50F;
boolean continueLoop = true;
Scanner input = new Scanner(System.in);
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
while (continueLoop) {
int option, confirm=0;
System.out.println("\t ##### Welcome to Zoos Victoria #####");
System.out.println("\t \t MAIN MENU \n");
System.out.println("\t Zoo has the following ticketing options \n");
System.out.println("\t 1 = Child (4-6 yrs)");
System.out.println("\t 2 = Adult (16+ yrs)");
System.out.println("\t 3 = Senior (60+ yrs) \n");
System.out.println("Enter your option:");
option = input.nextInt();
switch (option) {
case 1: {
System.out.println("Enter total No of tickets for Child:");
int quantity = input.nextInt();
childTotal = quantity * childCost;
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for child tickets: $" + childTotal);
}
break;
}
case 2: {
System.out.println("Enter total No of tickets for Adult:");
int quantity = input.nextInt();
adultTotal = quantity * adultCost ;
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for adult tickets $" + adultTotal);
}
break;
}
case 3: {
System.out.println("Enter total No of tickets for Senior:");
int quantity = input.nextInt();
seniorTotal = quantity * seniorCost ;
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for senior tickets $" + seniorTotal);
}
break;
}
}
if (confirm != 1) {
System.out.println("Incorrect key!");
}
System.out.println("Do you wish to continue? (Y/N) ");
char resume = input.next().charAt(0);
if (resume != 'y' && resume != 'Y') {
continueLoop = false;
System.out.println("Total amount for child tickets: $" + childTotal);
System.out.println("Total amount for senior tickets $" + seniorTotal);
System.out.println("Total amount for adult tickets $" + adultTotal);
float finalTotal = childTotal + adultTotal + seniorTotal ;
System.out.println("Total amount payable: $ " + finalTotal);
}
}
}
}
Try this code. I hope it helps.
public static void main(String[] args) {
int option, quantity, confirm; //minor change
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0; //minor change
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
}else{
continueLoop = false;
switch (option) {
case 1:
finalTotal+=(double) quantity*childTotal ; //minor change
System.out.println("Total amount payable: $" + childTotal);
break;
case 2:
finalTotal+=(double) quantity*adultTotal ; //minor change
System.out.println("Total amount payable $" + adultTotal);
break;
default:
finalTotal+=(double) quantity*seniorTotal; //minor change
System.out.println("Total amount payable $" + seniorTotal);
break;
}
}
}
}
}
I wished to play and did not fully understand the problem...so i developed from scratch the application. Suryakant was faster so please accept his answer (if it solves your problem). I simply post this here since i worked on it :-)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean continueLoop = true;
Map<TicketType, Integer> purchases=new HashMap<>();
do {
TicketType type = printMenu(scan);
System.out.println("Enter number of tickets for " + type.label);
int quantity = scan.nextInt();
System.out.println("You are purchasing "+quantity + " "+ type.label+ " ticket at "+type.cost+" each. " +
"Press 1 to confirm?");
int confirm= scan.nextInt();
if (confirm!=1) continue;
if (purchases.containsKey(type)){
purchases.put(type,purchases.get(type)+quantity);
System.out.println("You now have " +purchases.get(type) +" "+type.label +" tickets in total");
}else {
purchases.put(type,quantity);
}
System.out.println("You have added " +quantity +" "+type.label +" tickets in your basket.");
System.out.println("Do you wish to continue (Y|N)?");
String resume=scan.next();
if (resume.startsWith("Y") || resume.startsWith("y")){
continueLoop=true;
}else {
continueLoop=false;
}
}while (continueLoop);
System.out.println("Purchases");
long total=0;
for (Map.Entry<TicketType, Integer> ticketTypeIntegerEntry : purchases.entrySet()) {
System.out.println(ticketTypeIntegerEntry.getKey().label+"("+ticketTypeIntegerEntry.getValue()+")");
total+=ticketTypeIntegerEntry.getKey().cost*ticketTypeIntegerEntry.getValue();
}
System.out.println("Total payable ammount: "+total);
}
private static TicketType printMenu(Scanner scan) {
System.out.println("Welcome");
TicketType type;
int k = -1;
do {
for (TicketType ticketType : TicketType.values()) {
System.out.println(ticketType.id + ". for " + ticketType.label);
}
System.out.println("Enter your option");
k = scan.nextInt();
} while ((type=TicketType.valuefromId(k))==null);
return type;
}
private enum TicketType {
CHILD(1, "Child", 18D),
ADULT(2, "Adult", 36D),
SENIOR(3, "Senior", 18.5D);
int id;
String label;
double cost;
private static Map<Integer,TicketType> map=new HashMap<Integer,TicketType>();
static {
for (TicketType ticketType : TicketType.values()) {
map.put(ticketType.id,ticketType);
}
}
TicketType(int id, String label, double cost) {
this.id = id;
this.label = label;
this.cost=cost;
}
public static TicketType valuefromId(int id){
return map.get(id);
}
}
}
improvements are in reading.. i would check first if what i read is character or not..
Related
This question already has answers here:
Using variables outside of an if-statement
(2 answers)
Closed 2 years ago.
I'm a student and would like to know if there is a way to take a variable out of its scope block to be used in a local scope? I am trying to code a store of some sort where the users are given a few options to choose what they want to buy, how much they want to buy, and give them the total payment for the same Item. Now outside the block scope, I want to give the overall total with how much they bought of each item. Here's my code:
import java.util.Scanner;
public class SariSariStore{
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
int piattos = 20;
int wRabbit = 1;
int maxEM = 1;
int nescafeO = 7;
float iceW = 1.50f;
System.out.println("Would you like to buy something? [Y/N]");
char i = scanner.next().toLowerCase().charAt(0);
do {
System.out.println("==================================="
+"\n"+ "| Sari Sari Mart |"
+"\n"+ "==================================="
+"\n"+ "| What do you want to buy? |"
+"\n"+ "| |"
+"\n"+ "| 1) Piattos chips 20 Php |"
+"\n"+ "| 2) White Rabbit 1 Php |"
+"\n"+ "| 3) Max extra menthol 1 Php |"
+"\n"+ "| 4) Nescafe Original 7 Php |"
+"\n"+ "| 5) Ice water 1.5 PhP |"
+"\n"+ "| 6) Exit |"
+"\n"+ "===================================");
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
int itotal1 = piattos * quantity1;
System.out.println("Total price: " + itotal1 +" Php");
}else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
int itotal2 = wRabbit * quantity2;
System.out.println("Total price: " + itotal2 +" Php");
}else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
int itotal3 = maxEM * quantity3;
System.out.println("Total price: " + itotal3 +" Php");
}else if (choice == 4){
System.out.print("How many would you like to buy? " );
int quantity4 = scanner.nextInt();
int itotal4 = nescafeO * quantity4;
System.out.println("Total price: " + itotal4 +" Php");
}else if (choice == 5){
System.out.print("How many would you like to buy? " );
int quantity5 = scanner.nextInt();
float itotal5 = iceW * quantity5;
System.out.println("Total price: " + itotal5 +" Php");
}else if (choice == 6){
}
}else{
System.out.println ("Sorry we do not have that item, please pick among the choices");
}
int Total = itotal1 +itotal2 +itotal3 +itotal4 +itotal6; // problematic statement
System.out.println ("Your total is:"+ Total + " Php");
System.out.println ("Do you still want to buy something? [Y/N]");
i = scanner.next().toLowerCase().charAt(0);
}while (i == 'y');
if (i =='n'){
System.out.println("Thank you! Please come again");
}
}
}
Thanks :>
Can't you use just one field for this? Like this:
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
int total = 0;
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
total = piattos * quantity1;
System.out.println("Total price: " + total +" Php");
} else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
total = wRabbit * quantity2;
System.out.println("Total price: " + total +" Php");
} else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
total = maxEM * quantity3;
System.out.println("Total price: " + total +" Php");
}
...
} else {
System.out.println ("Sorry we do not have that item, please pick among the choices");
System.out.println ("Your total is:"+ total + " Php");
}
Also consider using switch statement for multiple if statements
I'm writing a party planner program for a question for class.
I can't initialize my three choices of entertainment, decorations, and food.
Eclipse tells me that I should set all these values to 0. I have to stick to these if else statements because that's what we have learned so far.
Here is my code:
import java.util.Scanner;
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
int budget = entertainment + decorations + food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}
The problem is
The local variable entertainment, decorations, and food may have not been initalized.
First , you have to make the sum at the end of the code because at first the variables are not initialized yet , and secondly you can assign a value of zero if no choice have been made , like this :
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
else { entertainment = 0; }
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
else { decorations = 0; }
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
else { food = 0 ; }
int budget = entertainment + decorations + food;
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}
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 just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}
Ok guys so I'm stuck trying to write some code in java, I cant get the code to display the pricing option for fullsize. I can't get the program to continue onto the second option I have listed as Case 2.
The project basically gives the user the option to ask if he is renting a car [Y or N]:
if Y is inputed the next question
it ask is "Compact of Full-size?",
if the user selects compact the project displays that the user has selected compact and
if the code displays fullsize the project displays that the user has selected fullsize.
Then it asks the user if they have a coupon if the users answer Y for the coupon the price is 7% off of 30.50.
If the user answers N the price is a normal 30.50. The fullsize normal price is 40.50 and the price with a coupon is 7% off of 40.50. The following is the code i have written currently.
The code:
public class CarRental {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50) - (30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50) - (40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye. ");
} else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
} else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
//case 2
response = input.next().toUpperCase();
if (response.equals("F")) {
System.out.println("You have selected Full-Size.");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
You're missing some }s after your else clauses. Example:
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//Put code that should only execute if you select Compact here.
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
//Put code that should only execute if you select Full-size here.
//Should have a } here!
//Put code that should always execute here.
Because you never close the block of code in the else clause, all of the code that follows is still part of the else, and therefore will only be executed if the else is selected, not under every circumstance as you had intended.
You are opening lots of brackets { but not closing them where you need }.
I usually not just handing the code, but I've noticed you done must of the job, but confused where to close the brackets and a little bit at the program flow.
I only changed it a bit, there is a lot that you can cut and reuse code.
public static void main(String[] args){
for(int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
}
else if(response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
The problem with this code is all your code is under the if statemente for Full-Size so the case 2 only executes when you select full-size , Yes to coupon and after showing the final message you press F again the code should look like this.
public class CarRental {
public static void main(String[] args){
for(int i=0; i<4; i++){
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
//case 2
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
As you can see in the code above is really important to correctly close conditional blocks so the code really does what you expect it to do.
Using flow diagrams is a good support for learning how programming languages really work.