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.
Related
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..
I would like this program below to capture user input (first product name, then costs), and then output to the console, and ask the user if they would like anything else, and if they do, it will do it again and output the next product and costs.
If the user replies with no, then I want it to output a list of the items by number and name, and then the total costs of how every many items were requested, and then a total overall cost.
Here is my code so far; I want to understand how to get the total overall costs and list each item. I feel like I am very close.
public static void main(String[] args) {
/////////Initialize everything here/////////
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR " + items + " ITEMS: " + "\nShipping (flat fee): " + shipping + "\nSum of Items: ");
}}
You need a list to hold item names and one temporary variable to hold sum of prices. I think below code will help you.
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
List<String> orderItems = new ArrayList<>();
double totalPrice=0;
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
orderItems.add(nameProd);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
totalPrice+=totAmt;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR ITEMS: " + orderItems + "\nShipping (flat fee): " + shipping + "\nSum of Items: "+totalPrice);
}
case 2:
System.out.println("Please enter Book ID: ");
String userinput2 = sc.next();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
System.out.println("BookID: " + myBooks.get(i).getBookID() + "\nTitle: "
+ myBooks.get(i).getTitle() + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("Please enter new details of book");
System.out.println("Title: ");
String userinput7 = sc.next();
myBooks.get(i).setTitle(userinput7);
System.out.println("Author: ");
String u1 = sc.next();
myBooks.get(i).setAuthor(u1);
myBooks.get(i).setOnLoan(false);
myBooks.get(i).setNumLoans(0);
System.out.println("---------------------------------------------------");
System.out.println("The book has been successfully updated");
System.out.println("Book ID: " + myBooks.get(i).getBookID() + " " + "\nTitle: "
+ myBooks.get(i).getTitle() + " " + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("---------------------------------------------------");
}
else { System.out.println("Please enter a correct bookID");
}
}
I'm having a problem with my validation check. If the user enters a bookID that doesn't exist, instead of printing out "please enter a correct bookID" once, it prints it out 4 times, which amounts to the number of objects i have in the array list. Is there a way to sort this?
Your else statement is in the middle of the for statement
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
[[do stuff]]
}
else { System.out.println("Please enter a correct bookID");
}
}
It looks like it should be in the middle of the if statement
if (myBooks.get(i).getBookID().contains(userinput2)) {
for (int i=...) {
[[do stuff]]
}
}
else { System.out.println("Please enter a correct bookID");
}
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;
}
I have been trying to figure out how to make it so players could choose to restart the game at the end, but whenever I try to restart the loop, it says
Label Game was not found
even though it is clearly shown in this code.
// System objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assassin"};
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;
int enemyDeaths = 0;
List scores = new ArrayList();
// Player variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
boolean running = true;
System.out.println("Welcome to the Dungeon!");
Game:
while(running) {
System.out.println("-----------------------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + " has appeared! #\n");
while(enemyHealth > 0) {
System.out.println("\tYour HP: "+ health);
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. Drink Health Potion");
System.out.println("\t3. Run");
String input = in.nextLine();
if(input.equals("1")) {
int damageDealt = rand.nextInt(attackDamage);
int damageTaken = rand.nextInt(enemyAttackDamage);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t> You strike the " + enemy + " for " + damageDealt + " damage. ");
System.out.println("\t> You received " + damageTaken + " in retaliation");
if(health < 1) {
System.out.println("\t> You have taken too much damage! You are too weak to go on!");
break;
}
}
else if(input.equals("2")) {
if(numHealthPotions > 0) {
health += healthPotionHealAmount;
numHealthPotions--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP"
+ "\n\t> You have " + numHealthPotions + " health potions left.\n");
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!");
}
}
else if(input.equals("3")) {
System.out.println("\tYou ran away from the " + enemy + "!");
continue Game;
}
else {
System.out.println("\tInvalid Command");
}
}
if(health < 1) {
System.out.println("You limp out of the dungeon, weak from battle");
break;
}
enemyDeaths++;
System.out.println("-----------------------------------------------");
System.out.println(" # " + enemy + " was defeated! #");
System.out.println(" # You have " + health + " HP left. #");
System.out.println(" # Your current score is " + enemyDeaths * 100 + " # ");
if(rand.nextInt(100) < healthPotionDropChance) {
numHealthPotions++;
System.out.println(" # The " + enemy + " dropped a health potion! #");
System.out.println(" # You have " + numHealthPotions + " health potion(s). # ");
}
System.out.println("-----------------------------------------------");
System.out.println("What would you like to do now?");
System.out.println("1. Continue fighting");
System.out.println("2. Exit Dungeon");
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 continue on your adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventures!");
scores.add(enemyDeaths * 100);
break;
}
}
System.out.println("######################");
System.out.println("# THANKS FOR PLAYING #");
System.out.println("######################");
String randomWords;
in = new Scanner(System.in);
System.out.println("Enter a name to be remembered by");
randomWords = in.next();
scores.add(randomWords + " " + enemyDeaths * 100);
System.out.println(scores);
System.out.println("\n");
System.out.println("\n");
{
System.out.println("Would you like to play again?");
String input = in.nextLine();
if(input.equals("yes")) {
continue Game;
}
}
}
}
To keep it simple, you could just change the exit criteria:
if (!input.equals("yes")) {
break; // end the loop
}
Just a hint: it is considered a good practice to compare a literal against some variable:
if (!"yes".equals(input)) {
break; // end the loop
}
Doing the check this way will not fail with NullPointerException in case input is null, it just returns false in this case.
it's easier if you set the opposite:
if(input.equals("no")) running = false;
That way the while loop gets out cleanly and you don't need to use a cumbersome label to control your flow.
From
Branching Statements
The continue statement skips the current iteration of a for, while , or do-while loop.
You want to jump to the label 'Game' from outside of the labelled while loop,
which is not allowed.