i m unable to calculate the total after loop - java

i m unable to calculate the total poperty price and commision help plzzz
my variables are prop and commission
program run perfect but the transaction summarry lead to last loop calculation i need to total all of loop calculation i made
import java.util.Scanner;
public class loopingS {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String code, decision;
int price =0;
double residential, commercial, multidwelling;
boolean yesno = true;
boolean repeat = true;
boolean cde = true;
double total=0;
boolean yn = true;
double prop=0;
double commission=0;
System .out.println("Real-estate Commission Calculator");
System.out.println("----------------------------------");
while (yn){
while(repeat){
System.out.print("Enter property's selling price: ");
price = kbd.nextInt();
if (price <= 0) {
System.out.println("**error**selling price must be greater than zero ");
repeat = true;
}
else{
prop=0 + price;
while(cde){
System.out.println("residential R\nmulti-dwelling M\nCommercial C");
System.out.println("Enter property code: ");
code = kbd.next();
switch(code){
case "r":
residential = price * 0.07;
cde = false;
total = +residential;
break;
case "m":
multidwelling = price * 0.06;
cde = false;
total = + multidwelling;
break;
case "c":
commercial = price * 0.035;
cde = false;
total = +commercial;
break;
default:
System.out.println("**error**- Property code must be R,M,C");
cde = true;
break;
}
commission=0 + total;
}
}
cde = true;
break;
}
System.out.println("Do u want to calculate another commission(y or n): ");
decision = kbd.next();
switch(decision){
case"y":
yn = true;
break;
case "n":
System.out.println("*********Transacction Summary************");
System.out.println("Total Property Sale: " +prop);
System.out.println("Total Commissions: " + commission);
yn = false;
break;
default :
System.out.println("**Error**Enter valid response");
yesno = true;
while(yesno){
System.out.println("do you want to calculate another commsion(y or n):");
decision = kbd.nextLine();
switch(decision){
case "y":
yn=yesno= true;
break;
case "n":
yn=yesno= false;
break;
}
}
}
}
}
}

import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String code, decision;
int price = 0;
double residential, commercial, multidwelling;
boolean yesno = true;
boolean repeat = true;
boolean cde = true;
double total = 0;
boolean yn = true;
double prop = 0;
double commission = 0;
System.out.println("Real-estate Commission Calculator");
System.out.println("----------------------------------");
while (yn)
{
while (repeat)
{
System.out.print("Enter property's selling price: ");
price = kbd.nextInt();
if (price <= 0)
{
System.out.println("**error**selling price must be greater than zero ");
repeat = true;
}
else
{
prop = prop + price;
while (cde)
{
System.out.println("residential R\nmulti-dwelling M\nCommercial C");
System.out.println("Enter property code: ");
code = kbd.next();
switch (code)
{
case "r":
residential = price * 0.07;
cde = false;
total = +residential;
break;
case "m":
multidwelling = price * 0.06;
cde = false;
total = +multidwelling;
break;
case "c":
commercial = price * 0.035;
cde = false;
total = +commercial;
break;
default:
System.out.println("**error**- Property code must be R,M,C");
cde = true;
break;
}
commission = commission + total;
}
}
cde = true;
break;
}
System.out.println("Do u want to calculate another commission(y or n): ");
decision = kbd.next();
switch (decision)
{
case "y":
yn = true;
break;
case "n":
System.out.println("*********Transacction Summary************");
System.out.println("Total Property Sale: " + prop);
System.out.println("Total Commissions: " + commission);
yn = false;
break;
default:
System.out.println("**Error**Enter valid response");
yesno = true;
while (yesno)
{
System.out.println("do you want to calculate another commsion(y or n):");
decision = kbd.nextLine();
switch (decision)
{
case "y":
yn = yesno = true;
break;
case "n":
yn = yesno = false;
break;
}
}
}
}
kbd.close();
}
}
Hope this solves your problem.

Related

Im not sure whats the problem with my code, as it displays invalid when i enter a valid date input

Im using Java and mySql
I have already done my code to prompt user to enter a date in the format DDMMYY and then store the info into the database, however, when i enter a valid date such as 121221, it will say "invalid date, please re-enter" Im not sure whats the problem..
this is my validation class
public class Validation {
public static boolean isValidDate(String date) {
String day = date.substring(0,2);
String month = date.substring(2,4);
String year = date.substring(4,6);
int i = Integer.parseInt(day);
int j = Integer.parseInt(year);
int k = Integer.parseInt(month);
if (k%2 !=0 || k == 8 || k == 10 || k == 12) {
if(i<=0 || i>31) {
return false;
}
}else if (k == 2) {
if(i<=0 || i>28) {
return false;
}
}else if (k%2 == 0 || k == 9 || k == 11) {
if (i<=0 || i>30) {
return false;
}
}
if(j<22 || j>100) {
return false;
}
return true;
}
public boolean isValidTransactionId(int transactionId) {
return true;
}
}
my UI class
package view;
import java.util.*;
import java.text.*;
import controller.DBController;
import controller.Validation;
import model.Transaction;
import model.Member;
public class UserInterface {
DBController db;
Validation vd;
Scanner scan;
Random rand;
String date;
boolean invalid;
int menuChoice, memberChoice;
Transaction transaction;
public UserInterface()throws Exception{
db= new DBController();
scan = new Scanner(System.in);
rand = new Random();
transaction = new Transaction();
}
public void MainMenu()throws Exception {
System.out.println("Welcome to SuperFun Theme Park!");
do {
System.out.print("Main Menu\n");
System.out.println("1. New Ticket Transaction");
System.out.println("2. Modify a Ticket Transaction");
System.out.println("3. Delete a Ticket Transaction");
System.out.println("4. View Ticket Transactions");
System.out.println("5. Exit");
System.out.print("Enter a number (1-5): ");
menuChoice = scan.nextInt();
scan.nextLine();
switch(menuChoice) {
case 1: newTicket(); break;
case 2: modifyTicket(); break;
case 3: deleteTicket(); break;
case 4: viewAllTransactions(); break;
case 5: System.out.println("Thank you. Have a nice day!"); break;
default: System.out.println("Invalid input. Please re-enter.\n");break;
}
}while(menuChoice!=5);
}
public void dateInput()throws Exception{
do {
if(menuChoice ==1 ) {
System.out.print("Enter ticket date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}else if (menuChoice == 4) {
System.out.print("Enter start date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}
invalid = false;
if(!vd.isValidDate(date)) {
invalid = true;
}else
invalid = false;
}while(invalid);
}
public void displayMemberInfo()throws Exception{
String result[] = null;
System.out.printf("\n%s %17s %20s\n","Index","Name", "Phone Number");
result = db.retrieveMemberInfo();
for(String temp: result)
System.out.println(temp);
}
public void newTicket() throws Exception{
int member=0, numOfMemberTickets=0, transactionId =0;
int memberTicket=80, nonMemberTicket=100, total=0, num=0;
boolean full = false, repeat= false;
//auto generate transaction id //100-200
int upperbound = 200;
int lowerbound = 100;
do {
transactionId = rand.nextInt(upperbound - lowerbound)+ lowerbound;
transaction.setId(transactionId);
}while(db.idExists(transaction.getId()));
//display transaction id
System.out.println("\nTransaction Id: " + transaction.getId());
//prompt user to enter ticket date
//validation for date
do {
dateInput();
db.maximumTicket(transaction.getDate());
if(db.sum>=100) {
System.out.println("Tickets are fully booked for the day. Please re-enter date.\n");
full = true;
}else {
System.out.printf("Number of tickets left for %s are %d\n" , date, 100-db.sum);
full = false;
}
}while(full);
//ask for total number of tickets then ask for members tickets
do {
System.out.print("Enter number of ticket(s) wanted: ");
num = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(num);
if(transaction.getTicketNum() > 100-db.sum)
System.out.println("Number of ticket(s) wanted exceeded availability. Please re-enter. ");
}while(transaction.getTicketNum() > 100-db.sum);
//if member, must choose which member
//loop through member info for validation
do {
repeat=false;
do {
System.out.print("Are there ticket(s) for member(s)? (1-yes 2-no): ");
member = scan.nextInt();
scan.nextLine();
if(member !=1 && member !=2)
System.out.println("Invalid input. Please re-enter.");
}while(member !=1 && member !=2);
if(member==1) {
do {
System.out.print("Enter the number of member tickets: ");
numOfMemberTickets = scan.nextInt();
scan.nextLine();
if(numOfMemberTickets<=0)
System.out.println("Invalid number of tickets. Please re-enter.");
}while(numOfMemberTickets<=0);
//display member info table
displayMemberInfo();
for(int cnt=0; cnt<numOfMemberTickets; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
// if(db.memberExists(transaction.getId())) {
// System.out.println("Member are only allowed to purchase one ticket in a day. Please re-enter.");
// repeat = true;
// }else
db.insertNumber(memberChoice, transaction.getId());
}while(memberChoice<=0);
}
}
}while(repeat);
//calculate and display total price
total = (numOfMemberTickets * memberTicket) + (Math.abs((transaction.getTicketNum() - numOfMemberTickets)) * nonMemberTicket);
transaction.setTotal(total);
System.out.println("Total price: RM" + transaction.getTotal());
//save data into database
boolean success = db.insertInfo(transaction.getDate(), transaction.getId(), transaction.getTicketNum(), transaction.getTotal());
if(success)
System.out.println("Transaction record inserted successfully.\n");
else
System.out.println("Error in inserting record.\n");
}
public void modifyTicket() throws Exception{
int transactionId=0, newTicketNum=0, newNumOfMemberTicket=0, newTotal=0, change=0;
String newDate="";
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
transaction.setId(transactionId);
if(!db.idExists(transaction.getId()))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transaction.getId()));
//display details
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transaction.getId());
//user can edit date, number and members' phone number
System.out.print("\nEnter new ticket date: ");
newDate = scan.nextLine();
transaction.setDate(newDate);
System.out.print("Enter new number of tickets(including members' tickets): ");
newTicketNum = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(newTicketNum);
System.out.print("Enter new number of member ticket(s): ");
newNumOfMemberTicket = scan.nextInt();
scan.nextLine();
System.out.print("Is there a change in member(s)? (1-yes 2-no): ");
change = scan.nextInt();
scan.nextLine();
if(change==1) {
displayMemberInfo();
for(int cnt=0; cnt<newNumOfMemberTicket; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
db.updateNumber(memberChoice, transactionId);
}while(memberChoice<=0);
}
}
//recalculate total price
newTotal = (newNumOfMemberTicket * 80) + (Math.abs(newTicketNum - newNumOfMemberTicket)* 100);
transaction.setTotal(newTotal);
//update database
boolean success = db.updateInfo(transaction.getDate(), transaction.getTicketNum(), transaction.getTotal(), transaction.getId());
if(success)
System.out.println("Information updated successfully.\n");
else
System.out.println("Error in updating information.\n");
}
public void deleteTicket()throws Exception{
int transactionId=0, choice =0;
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
if(!db.idExists(transactionId))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transactionId));
transaction.setId(transactionId);
//display all information of that transaction
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transactionId);
//re-confirm whether to delete
do {
System.out.print("\nConfirm delete? (1-yes 2-no): ");
choice = scan.nextInt();
}while(choice !=1 && choice !=2);
//delete from database
if(choice == 1) {
boolean success = db.deleteInfo(transaction.getId());
if (success)
System.out.println("Transaction Info deleted successfully.\n");
else
System.out.println("Error in deleting transaction info.\n");
}else
System.out.println("Returning to main menu...\n");
}
public void viewAllTransactions() throws Exception{
String result[] = null;
String date2 ="", letter="";
//enter start date
dateInput();
switch(date.substring(2,4)) {
case "01": letter = "Jan"; break;
case "02": letter = "Feb"; break;
case "03": letter = "Mar"; break;
case "04": letter = "Apr"; break;
case "05": letter = "May"; break;
case "06": letter = "June"; break;
case "07": letter = "July"; break;
case "08": letter = "Aug"; break;
case "09": letter = "Sep"; break;
case "10": letter = "Oct"; break;
case "11": letter = "Nov"; break;
case "12": letter = "Dec"; break;
}
date2 = date.substring(0,2) + letter + "20" + date.substring(4,6);
//show all records from start date
//display error if no matching one
boolean success = db.matchingDate(transaction.getDate());
if(success) {
System.out.println("\nTransaction Report from " + date2);
System.out.printf("%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
result = db.retrieveAllInfo(date);
for(String temp: result)
System.out.println(temp);
}else
System.out.println("Error in finding date entered.");
System.out.println("\nReturning to main menu...\n");
}
}
transaction class
public void setDate(String date) {
if(Validation.isValidDate(date))
this.date = date;
else
System.out.println("Date is invalid. Please re-enter.");
}
Honestly, those if checks are kind of hard to look at. Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class dateTime {
public static void main(String[] args) throws ParseException {
SimpleDateFormat datefr = new SimpleDateFormat("dd-MM-yy");
datefr.setTimeZone(TimeZone.getTimeZone("UTC"));
datefr.setLenient(false);
try {
Date date = datefr.parse("12-10-21");
System.out.println(true);
} catch (ParseException e) {
System.out.println(false);
System.out.println(e.getMessage());
}
}
}

Not able to take input in java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
This is my code, here when i input the Product name i.e. Laptop/Mobile and then input the price. after that the program does not input eask and simply goes to the eask if-else case and prints the Invalid option as:
import java.util.*;
class Main {
public static void main(String[] args) {
int discount=0,ediscount=1;
Scanner sc = new Scanner(System.in);
String Product = sc.nextLine();
int Price = sc.nextInt();
String eask = sc.nextLine();
if(Price>100){
if(eask == "Yes" || eask == "No"){
if(Product == "Mobile"){
discount = 10;
if(eask == "Yes")
ediscount=12;
}
else if(Product == "Laptop"){
discount = 20;
if(eask == "Yes")
ediscount=10;
}
else if(Product == "gadgets"){
discount = 0;
if(eask == "Yes")
ediscount=0;
}
else System.out.println("Invalid product");
}
else
System.out.println("Invalid option");
}
else System.out.println("Invalid price");
float TBA = discount * Price;
System.out.println(TBA);
}
}
Try this:
int discount=0,ediscount=1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter product name : ");
String Product = sc.next();
System.out.print("Enter product price : ");
int Price = sc.nextInt();
System.out.print("Enter eask : ");
String eask = sc.next();
if(Price>100){
if(eask.equals("Yes") || eask.equals("No") ){
switch (Product) {
case "Mobile":
case "mobile":
discount = 10;
if("Yes".equals(eask))
ediscount=12;
break;
case "Laptop":
case "laptop":
discount = 20;
if("Yes".equals(eask))
ediscount=10;
break;
case "Gadgets":
case "gadgets":
discount = 0;
if("Yes".equals(eask))
ediscount=0;
break;
default:
System.out.println("Invalid product");
break;
}
}
else
System.out.println("Invalid option");
}
else System.out.println("Invalid price");
float TBA = discount * Price;
System.out.println("The price is : " + TBA);

Craps Project - Debugs for non apparent syntax errors

I'm making a bare-bones Craps simulator with Java on the Eclipse IDE, I'm having a terribly hard time debugging the things that don't seem to indicate any errors in syntax only during the compiling process.
I'm running into this issue when trying to assign a value to the first bet on the "table."
The Pass()method isn't operating as I expected it would, I don't have any immediate error messages however it does not want to compile past this point, which is only line 33 down on the main method.
char answer = keyboard.nextLine().toUpperCase().charAt(0); This line seems to be the largest hurdle in getting all of my methods to operate smoothly throughout.. from what I understand.
I do have a die class but that's proving to be a non issue so I didn't include it in this post.
EDIT: This is the entirety of the program as it stands. I've been tweaking left and right on either end to find the appropriate ways to compile this absolute mess.
Any input is much appreciated. Thank you in Advance.
import java.util.Scanner;
public class Craps {
//Declaring start value of balances
static double totalMoney = 0.00;
static double rollMoney = 0.00;
public static void main(String[] args) {
//Creating Die Objects
Die die1 = new Die();
Die die2 = new Die();
//Beginning of loop
do {
//Displaying the rules for the game
displayMenu();
//Array to hold both Dice and create total for the first roll
//as well as every roll there after
//Initialized 'purses' for the first bets
int dice[] = new int[2];
int intTotal = 0;
int total = 0;
int passBet = 2;
double pass = 0.00;
double dontPass = 0.00;
//Rolling Dice for the first time in the Round
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
intTotal = (dice[0] + dice[1]);
//Assigning Value to Pass/Don't Pass bets
do {
while(Pass() == true) {
try{
pass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
while(dontPass() == true) {
try{
dontPass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
//Display of each individual rolls
//Display of total
//Win-Loss-Continue Play check
switch(intTotal) {
case 7:
case 11:
rollMoney = (pass*passBet);
dontPass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Don't Pass line, better luck next time.");
System.out.println("You have made: " + pass);
System.out.println("Total Earnings: " + totalMoney);
case 2:
case 3:
case 12:
rollMoney = (dontPass*passBet);
pass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Pass line, better luck next time.");
System.out.println("You have made: " + dontPass);
System.out.println("Total Earnings: " + totalMoney);
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
//"Actual" Game of Craps
do {
double placeBet[] = {1.2, 1.5, 2.0};
int hardBet[] = {7, 9};
int hornBet[] = {15, 30};
//List<Double> place = new ArrayList<Double>();
//List<Double> hard = new ArrayList<Double>();
//List<Double> horn = new ArrayList<Double>();
double place[] = new double[6];
double hard[] = new double[4];
double horn[] = new double[4];
int pBetMax = 6;
int haBetMax = 4;
int hoBetMax = 4;
int pBets[] = new int[pBetMax];
int haBets[] = new int[haBetMax];
int hoBets[] = new int[hoBetMax];
//Gathering Place Bets w/ Location and Value
if(Place() == true) {
pBets = getPlace();
for(int pBetOffset = 1; pBetOffset <= pBetMax; pBetOffset++) {
switch(pBets[pBetOffset]) {
case 4:
place[0] += getBet();
case 5:
place[1] += getBet();
case 6:
place[2] += getBet();
case 8:
place[3] += getBet();
case 9:
place[4] += getBet();
case 10:
place[5] += getBet();
case 0:
break;
}
}
}
//Gathering Hardway Bets w/ Location and Value
if(Hard() == true) {
haBets = getHard();
for(int haBetOffset = 1; haBetOffset <= haBetMax; haBetOffset++) {
switch(haBets[haBetOffset]) {
case 4:
hard[0] += getBet();
case 6:
hard[1] += getBet();
case 8:
hard[2] += getBet();
case 10:
hard[3] += getBet();
case 0:
break;
}
}
}
//Gathering Horn Bets w/ Location and Value
if(Horn() == true) {
hoBets = getHorn();
for(int hoBetOffset = 1; hoBetOffset <= hoBetMax; hoBetOffset++) {
switch(hoBets[hoBetOffset]) {
case 2:
horn[0] += getBet();
case 3:
horn[1] += getBet();
case 11:
horn[2] += getBet();
case 12:
horn[3] += getBet();
case 0:
break;
}
}
}
//Redefining the roll separate from the intRoll
dice = new int[2];
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
total = (dice[0] + dice[1]);
if(intTotal != total) {
switch(total) {
case 11:
rollMoney += (horn[2] * hornBet[1]);
case 2:
rollMoney += (horn[0] * hornBet[2]);
case 3:
rollMoney += (horn[1] * hornBet[1]);
case 12:
rollMoney += (horn[3] * hornBet[2]);
case 4:
if(dice[0]== dice[1]) {rollMoney += (hard[0] * hardBet[1]);}
rollMoney += (place[0] * placeBet[3]);
case 5:
rollMoney += (place[1] * placeBet[2]);
case 6:
if(dice[0]== dice[1]) {rollMoney += (hard[1] * hardBet[2]);}
rollMoney += (place[2] * placeBet[1]);
case 8:
if(dice[0]== dice[1]) {rollMoney += (haBets[2] * hardBet[2]); }
rollMoney += (place[3] * placeBet[1]);
case 9:
rollMoney += (place[4] * placeBet[2]);
case 10:
if(dice[0]== dice[1]) {rollMoney += (haBets[3] * hardBet[1]);}
rollMoney += (place[5] * placeBet[3]);
case 7:
//Wiping the bets clean off the board
pass = 0.00;
place = new double[10];
hard = new double[10];
horn = new double[10];
//Redefining the initial roll for the game
intTotal = 0;
total = 0;
totalMoney += (dontPass * 2);
crapOut();
}
}
}while(crapOut() == true);
}
}while(keepPlaying() == true);
}while(displayMenu() == true);
}
/*
* This method determines if the player will continue after the round is over
*/
public static boolean keepPlaying() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("");
System.out.println("Do you want to roll some more? (Y/N)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
public static boolean crapOut() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("Crap Out! All Bets are OFF!");
System.out.println("After this roll you now have: $" + rollMoney + " on the board!");
System.out.println("Which bring's your grand total to.. $" + (totalMoney + rollMoney));
System.out.println("Care to make another wager?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
/*
* This method will assign values to all the bets available to the player
*/
public static double getBet() {
System.out.println("How much would you like to bet?");
Scanner keyboard = new Scanner(System.in);
String bet = keyboard.nextLine();
float num;
num = Float.parseFloat(bet);
keyboard.close();
return num;
}
/*
* This method will ask if the player would like to Accept or Press their bet
*/
public static boolean pressBet(int bet) {
Scanner keyboard = new Scanner(System.in);
boolean press = false;
System.out.println("Press your bet? (Double your initial wager)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
press = answer == 'Y';
bet = bet * 2;
keyboard.close();
return press;
}
/*
* Methods to check if play would like to place wager
* Methods to assign those bets to appropriate places on the table
*/
public static boolean Pass() {
Scanner keyboard = new Scanner(System.in);
boolean pass = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
pass = answer == 'y';
keyboard.close();
return pass;
}
public static boolean dontPass() {
Scanner keyboard = new Scanner(System.in);
boolean dontPass = false;
System.out.println("Would you like to make a Don't Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
dontPass = answer == 'Y';
keyboard.close();
return dontPass;
}
public static boolean Place() {
Scanner keyboard = new Scanner(System.in);
boolean place = false;
System.out.println("Would you like to make a Place Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
place = answer == 'Y';
keyboard.close();
return place;
}
public static int[] getPlace() {
int counter = 1;
int max = 6;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[6];
do {
System.out.println("Make selections from the numbers (4, 5, 6, 8, 9, 10), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Horn() {
Scanner keyboard = new Scanner(System.in);
boolean horn = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
horn = answer == 'Y';
keyboard.close();
return horn;
}
public static int[] getHorn() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make selections from the numbers (2, 3, 11, 12), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Hard() {
Scanner keyboard = new Scanner(System.in);
boolean hard = false;
System.out.println("Would you like to make a Hardway Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
hard = answer == 'Y';
keyboard.close();
return hard;
}
public static int[] getHard() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make a selection from the numbers (4 (2&2), 6 (3&3), 8(4&4), 10(5&5)");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
/*
* Method to display rules and parameters of game prior to playing
*/
public static boolean displayMenu() {
System.out.println("Welcome to the Crosby Casino!");
System.out.println("The Game is Craps, Rules Are:");
System.out.println("If a 7 or 11 is the first roll on the table,");
System.out.println("Pass bets get paid on the first roll!");
System.out.println("If a 2, 3, or 12 is the first roll on the table, ");
System.out.println("Don't pass bets get paid on the first roll!");
System.out.println("If any other value is rolled, the game begins..");
System.out.println("Pass bets believe whatever other value was rolled will appear before the next 7 does.");
System.out.println("Don't Pass bets believe that the 7 will appear before the initial roll's value is shown again.");
System.out.println("During the duration of the roll you can make up to 3 separate side bets");
System.out.println("'Place bets' - (2, 5, 6, 8, 9, 10) Which pay out every time these numbers appear following the initial roll");
System.out.println("'Hard bets' - (4, 6, 8, 10) Which has the most coverage of all potential outcomes");
System.out.println(" & 'Horn bets' - (2, 3, 11, 12) The best payout odds on the table");
System.out.println("The table minimum is $5.00 to play");
System.out.println("All side bet minimums are $1.00 to play");
Scanner keyboard = new Scanner(System.in);
boolean menu = false;
System.out.println("Would you like play?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
menu = answer == 'Y';
keyboard.close();
return menu;
}
}
Java arrays are 0-origin. Basically, that means that the first element in arrays have an index of 0, not 1, as your dice array shows. Thus, you need to replace dice[1] and dice[2] with dice[0] and dice[1], respectively.
EDIT Based on new info from comments:
This sounds like a new error than the AIOOBE that you previously described. The issue with your code is that you need to ensure that you use Scanner's hasNextLine() method before calling the nextLine() method. Essentially, you are calling nextLine() when there is no "next line", causing the NoSuchElementException.

Java Fast Food Menu (using methods)

I'm writing a program that displays a fast food menu. The user selects an item, then enters the quantity of that item, and can continue selecting items with specific quantities until done. I have to use several methods. What I'm having trouble with is calculating a running total. This is my first Java class so I only know the basics. I put the running total in a while loop so it'll keep adding a subtotal to it, but when I call done() the runningTotal is 0. What's the best way to keep track of the running total while using multiple methods? Also, I'm open to any criticism or clean up in my code. Thank you.
import java.util.Scanner;
public class Menu {
public double subTotal;
public static double runningTotal;
private static double itemPrice;
static boolean ordering = true;
static Scanner input = new Scanner(System.in);
public static void menu() {
System.out.println("Welcome \n1. Burger ($2.00) \n2. Fries ($1.50)\n3. Soda ($1.00) \n4. Done");
}
public static double itemPrice(int foodItem) {
if (foodItem == 1) {
// burger= $2.00
System.out.println("You've ordered a burger");
itemPrice = 2.00;
}
if (foodItem == 2) {
// fries = $1.50
System.out.println("You've ordered fries");
itemPrice = 1.50;
}
if (foodItem == 3) {
// soda = $1.00
System.out.println("You've ordered a soda");
itemPrice = 1.00;
}
quantity();
return itemPrice;
}
public static double quantity() {
System.out.println("Enter quantity");
double quantity = input.nextDouble();
subTotal(quantity, itemPrice);
return quantity;
}
public static double subTotal(double quantity, double itemPrice) {
double subTotal = quantity * itemPrice;
System.out.println("Subtotal: " + subTotal);
return subTotal;
}
public static void done(double runningTotal) {
ordering = false;
System.out.println(runningTotal);
System.out.println("Enjoy your meal");
}
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
do {
double runningTotal = 0;
menu();
menuOption = input.nextInt();
switch (menuOption) {
case 1:
foodItem = 1;
itemPrice(foodItem);
break;
case 2:
foodItem = 2;
itemPrice(foodItem);
break;
case 3:
foodItem = 3;
itemPrice(foodItem);
break;
case 4:
done(runningTotal);
break;
default:
System.out.println("Invalid option.");
}
} while (ordering);
{
subTotal(quantity(), itemPrice(foodItem));
runningTotal = runningTotal + subTotal(quantity(), itemPrice(foodItem));
}
}
}
You are resetting the double runningTotal=0; in the while loop. Also the price returned by the itemPrice needs to be added into the runningTotal variable;
This is how your main method should look like. You are not required to call the subTotal method, once the user is done.
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
double runningTotal=0;
do{
menu();
menuOption = input.nextInt();
switch(menuOption){
case 1:
foodItem = 1;
runningTotal += itemPrice(foodItem);
break;
case 2:
foodItem = 2;
runningTotal += itemPrice(foodItem);
break;
case 3:
foodItem = 3;
runningTotal += itemPrice(foodItem);
break;
case 4:
done(runningTotal);
break;
default:
System.out.println("Invalid option.");
}
} while(ordering);
System.out.println("Total amount: " + runningTotal);
}
Output:
Welcome
1. Burger ($2.00)
2. Fries ($1.50)
3. Soda ($1.00)
4. Done
1
You've ordered a burger
Enter quantity
2
Subtotal: 4.0
Welcome
1. Burger ($2.00)
2. Fries ($1.50)
3. Soda ($1.00)
4. Done
2
You've ordered fries
Enter quantity
1
Subtotal: 1.5
Welcome
1. Burger ($2.00)
2. Fries ($1.50)
3. Soda ($1.00)
4. Done
4
3.5
Enjoy your meal
Total amount: 3.5
You reset runningTotal to 0 every iteration. I have attached a working example. I moved the total calculation to your subTotal method where it adds every subTotal as they come in.
import java.util.Scanner;
public class menu {
public double subTotal;
public static double runningTotal;
private static double itemPrice;
static boolean ordering = true;
static Scanner input = new Scanner(System.in);
public static void menu(){
System.out.println("Welcome \n1. Burger ($2.00) \n2. Fries ($1.50)\n3. Soda ($1.00) \n4. Done");
}
public static double itemPrice(int foodItem) {
if (foodItem == 1) {
//burger= $2.00
System.out.println("You've ordered a burger");
itemPrice = 2.00;
}
if (foodItem == 2) {
//fries = $1.50
System.out.println("You've ordered fries");
itemPrice = 1.50;
}
if (foodItem == 3) {
//soda = $1.00
System.out.println("You've ordered a soda");
itemPrice = 1.00;
}
quantity();
return itemPrice;
}
public static double quantity() {
System.out.println("Enter quantity");
double quantity = input.nextDouble();
subTotal(quantity, itemPrice);
return quantity;
}
public static double subTotal(double quantity, double itemPrice) {
double subTotal = quantity*itemPrice;
System.out.println("Subtotal: "+ subTotal);
runningTotal += subTotal;
return subTotal;
}
public static void done(){
ordering = false;
System.out.println(runningTotal);
System.out.println("Enjoy your meal");
}
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
do{
double runningTotal=0;
menu();
menuOption = input.nextInt();
switch(menuOption){
case 1:
foodItem = 1;
itemPrice(foodItem);
break;
case 2:
foodItem = 2;
itemPrice(foodItem);
break;
case 3:
foodItem = 3;
itemPrice(foodItem);
break;
case 4:
done();
break;
default:
System.out.println("Invalid option.");
}
} while(ordering); {
}
}
}
This will bring the exact output.
import java.util.Scanner;
public class Resteraunt
{
public double subTotal;
public static double runningTotal;
private static double itemPrice;
static boolean ordering = true;
static Scanner input = new Scanner(System.in);
static double j=0.0;
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
double runningTotal=0;
while(ordering)
{
menu();
menuOption = input.nextInt();
switch(menuOption){
case 1:
foodItem = 1;
runningTotal += ItemPrice(foodItem);
break;
case 2:
foodItem = 2;
runningTotal += ItemPrice(foodItem);
break;
case 3:
foodItem = 3;
runningTotal += ItemPrice(foodItem);
break;
case 4:
done(runningTotal);
break;
default:
System.out.println("Invalid option.");
}
}
System.out.println("Total amount: $" + runningTotal);
}
public static void menu() {
System.out.println("Welcome \n1. Burger ($2.00) \n2. Fries ($1.50)\n3. Soda
($1.00) \n4. Done");
}
public static double ItemPrice(int foodItem) {
if (foodItem == 1) {
// burger= $2.00
System.out.println("You've ordered a burger");
itemPrice = 2.00;
}
if (foodItem == 2) {
// fries = $1.50
System.out.println("You've ordered fries");
itemPrice = 1.50;
}
if (foodItem == 3) {
// soda = $1.00
System.out.println("You've ordered a soda");
itemPrice = 1.00;
}
quantity();
return j;
}
public static double quantity() {
System.out.println("Enter quantity");
double quantity = input.nextDouble();
subTotal(quantity, itemPrice);
return quantity;
}
public static double subTotal(double quantity, double itemPrice) {
double subTotal = quantity * itemPrice;
System.out.println("Subtotal: $" + subTotal);
j=subTotal;
return subTotal;
}
public static void done(double runningTotal) {
ordering = false;
System.out.println("Enjoy your meal");
}
}

Having issues with a menu function and a case switch function for a simple calculator

I'm trying to write a simple calculator with 2 functions (for right now). I'm using Java in Eclipse. I can't get what I'm currently attempting to work. I want to have just the menu item as its own function and then the case switch to be its own function after taking in the entryChoice. When I run this code as is and I make a selection all it does is repeats "Enter two numbers..." OR if I separate the userInput into each case to be printed after the entryChoice is passed, it breaks. Any advice?
public static void main(String[] args) {
// TODO Auto-generated method stub
displayMenu();
Scanner scanChoice = new Scanner(System.in);
int entryChoice = scanChoice.nextInt();
while (entryChoice != 7)
{
userSelection(entryChoice);
}
System.exit(0);
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice)
{
double result = 0;
System.out.println("Enter two numbers seperated by a space");
Scanner userInput = new Scanner(System.in);
double x = userInput.nextDouble();
double y = userInput.nextDouble();
switch (entryChoice)
{
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
result = x / y;
break;
case 5:
result = Math.pow(x,y);
break;
case 6:
System.out.println("Enter one number: "); // some kinks to work out here..
result = Math.sqrt(x);
break;
case 7:
result = 0;
break;
default:
}
return result;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
displayMenu();
Scanner scanChoice = new Scanner(System.in);
int entryChoice = scanChoice.nextInt();
while (entryChoice != 7) {
System.out.println(userSelection(entryChoice));
displayMenu();
entryChoice = scanChoice.nextInt();
}
System.exit(0);
}
public static void displayMenu() {
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice) {
Scanner userInput = new Scanner(System.in);
double x = 0;
double y = 0;
double result = 0;
if (entryChoice == 6) {
System.out.println("Enter one number: ");
x = userInput.nextDouble();
} else {
System.out.println("Enter two numbers seperated by a space");
x = userInput.nextDouble();
y = userInput.nextDouble();
}
switch (entryChoice) {
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
result = x / y;
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
result = 0;
break;
default:
}
return result;
}
I think what you want to have is the following:
public static void main(String[] args) {
// TODO Auto-generated method stub
int entryChoice = -1;
while (entryChoice != 7)
{
displayMenu();
Scanner scanChoice = new Scanner(System.in);
entryChoice = scanChoice.nextInt();
if (entryChoice != 7)
System.out.println(userSelection(entryChoice));
}
System.exit(0);
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice)
{
double result = 0;
System.out.println("Enter two numbers seperated by a space");
Scanner userInput = new Scanner(System.in);
double x = userInput.nextDouble();
double y = userInput.nextDouble();
switch (entryChoice)
{
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
result = x / y;
break;
case 5:
result = Math.pow(x,y);
break;
case 6:
System.out.println("Enter one number: "); // some kinks to work out here..
result = Math.sqrt(x);
break;
default:
}
return result;
}
Please try this, it is working as per your expectation
import java.util.*;
class Calculator
{
public static void main(String[] args) {
// TODO Auto-generated method stub
displayMenu();
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
Scanner scanChoice = new Scanner(System.in);
int entryChoice = scanChoice.nextInt();
while (entryChoice != 7)
{
userSelection(entryChoice);
}
System.exit(0);
}
public static double userSelection(int entryChoice)
{
double result = 0;
System.out.println("Enter two numbers seperated by a space");
Scanner userInput = new Scanner(System.in);
double x = userInput.nextDouble();
double y = userInput.nextDouble();
switch (entryChoice)
{
case 1:
result = x + y;
System.out.println("Result is :"+result);
break;
case 2:
result = x - y;
System.out.println("Result is :"+result);
break;
case 3:
result = x * y;
System.out.println("Result is :"+result);
break;
case 4:
result = x / y;
System.out.println("Result is :"+result);
break;
case 5:
result = Math.pow(x,y);
System.out.println("Result is :"+result);
break;
case 6:
System.out.println("Enter one number: "); // some kinks to work out here..
result = Math.sqrt(x);
System.out.println("Result is :"+result);
break;
case 7:
result = 0;
break;
default:
}
displayMenu();
return result;
}
}

Categories