Pizzas purchased program Java *FIXED* - java

Entry level java program that won't compile. Any help at all would be amazing! I really just need a quick review of my basic level code. I get errors for ints, booleans, and doubles. I've tried to rearrange them in multiple ways and i just can not get it to work. Also my Cheesy crust calculation to add it the total. Again super novice but would really enjoy the help!
import java.util.Scanner;
public class programmingassignment1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner( System.in );
int pizzaLength;
int pizzaWidth;
int pizzaShape;
double pizzaDiamiter;
double pizzaToppingPrice = 0.025;
int numberOfPizzaToppings;
double pizzaSauceAndCheese = 0.036;
double pizzaDoughPrice = 0.019;
char doughType;
String dough;
int numberOfPizzas;
double pizzasBeforeTax;
int cheesyCrustInput;
int deliveryWantedInput;
int deliveryCharge;
double doughVolume;
double area;
double crustCost;
int basePrice;
int costOfPizzaWithTax;
//Shape of pizza
System.out.println("What shape of pizza requested?");
System.out.println("Enter (1) for Rectange or (2) Round?");
pizzaShape = keyboard.nextLine().charAt(0);
if(pizzaShape == 1){
System.out.println("What Length?");
pizzaLength = keyboard.nextInt();
System.out.println("What Width?");
pizzaWidth = keyboard.nextInt();
area = pizzaLength * pizzaWidth;
}
else if(pizzaShape == 2){
System.out.println("What is the Diamiter?");
pizzaDiamiter = keyboard.nextInt();
area = Math.PI * (pizzaDiamiter / 2);
}
//Volume
System.out.print("What type of dough do you want? (1)Classic Hand-Tossed, (2)Thin and Crispy, (3)Texas Toast, or (4)Pan. (enter 1,2,3, or 4.");
doughType = keyboard.nextLine().charAt(0);
if (doughType == 1) {
dough = "Classic Hand-Tossed";
doughVolume = area * .25;
}
else if (doughType == 2) {
dough = "Thin and Crispy";
doughVolume = area * .1;
}
else if (doughType == 3) {
dough = "Texas Toast";
doughVolume = area * .9;
}
else if (doughType == 4) {
dough = "Pan";
doughVolume = area * .5;
}
//Cheesey crust
if(doughType == 2){
}
else{
System.out.println("Would you like cheesy crust? (1) for yes (2) for no");
cheesyCrustInput = keyboard.nextInt();
if(cheesyCrustInput == 1){
crustCost = area * .02;
String Crust = "";
}
else{
String Crust = "NO";
}
}
//Toppings
System.out.print("Enter the number of toppings:");
numberOfPizzaToppings = keyboard.nextInt();
if(numberOfPizzaToppings == 0){
String toppings = "no";
}
else{
int toppings = numberOfPizzaToppings;
}
//Base price
basePrice = area (pizzaSauceAndCheese + (pizzaToppingPrice * numberOfPizzaToppings) + (pizzaDoughPrice * doughVolume));
//how many pizzas
System.out.print("Enter the number of pizzas being ordered:");
numberOfPizzas = keyboard.nextInt();
pizzasBeforeTax = basePrice * numberOfPizzas;
//tax
costOfPizzaWithTax = pizzasBeforeTax ( 1 + 0.07);
//delivery fee
System.out.print("Would you like delivery? (1) for yes, (2) for no.");
deliveryWantedInput = keyboard.nextInt();
if(deliveryWantedInput == 1){
String deliveryOutput = numberOfPizzas + "deliverd";
if(costOfPizzaWithTax < 10){
deliveryCharge = 3;
}
if( 10 < costOfPizzaWithTax && costOfPizzaWithTax < 20 ){
deliveryCharge = 2;
}
if(20 < costOfPizzaWithTax && costOfPizzaWithTax < 30){
deliveryCharge = 1;
}
if(costOfPizzaWithTax > 30){
deliveryCharge = 0;
}
}
else{
String deliveryOutput = "no delivery";
}
//display total
total = costOfPizzaWithTax + deliveryCharge;
System.out.println("Total Due: $" + df.format(total));
if(pizzaShape = 1){
System.out.print("User requested: Rectangular, " + pizzaWidth + "X" + pizzaLength + ", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println("Details for - Rectangular Pizza (" + pizzaWidth + "\" X " + pizzaLength + "\"):");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
else{
System.out.print("User requested: Circular, " + pizzaDiamiter + "\", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
}
}
Fixed content follows below!
import java.util.Scanner;
public class programmingassignment1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
final double PIZZA_TOPPING_PRICE = 0.025;
final double PIZZA_SAUCE_AND_CHEESE = 0.036;
final double PIZZA_DOUGH_PRICE = 0.019;
double numberOfPizzaToppings;
double crustCost;
double basePrice;
double radiusOfPizza;
double sizeOfPizzaCrust;
double pizzasBeforeTax;
double pizzaLength = 1;
double pizzaWidth = 1;
double pizzaShape = 1;
double pizzaDiamiter = 0;
double doughType = 1;
double numberOfPizzas = 0;
double cheesyCrustInput = 0;
double deliveryWantedInput = 0;
double deliveryCharge = 0;
double doughVolume = 1;
double area = 1;
double costOfPizzaWithTax = 1;
double total = 1;
double toppings = 1;
String dough = "";
String crust = "";
String deliveryOutput;
String cheesyOutput = "";
// Shape of pizza
System.out.println("What shape of pizza requested?");
System.out.println("Enter (1) for Rectangle or (2) Round:");
pizzaShape = keyboard.nextDouble();
if (pizzaShape == 1) {
System.out.println("What Length?");
pizzaLength = keyboard.nextDouble();
System.out.println("What Width?");
pizzaWidth = keyboard.nextDouble();
area = pizzaLength * pizzaWidth;
} else if (pizzaShape == 2) {
System.out.println("What is the Diamiter?");
pizzaDiamiter = keyboard.nextDouble();
radiusOfPizza = pizzaDiamiter / 2;
area = Math.PI * radiusOfPizza * radiusOfPizza;
}
// Volume
System.out.print("What type of dough do you want? (1)Classic Hand Tossed,"
+ " (2)Thin and Crispy, (3)Texas Toast, or (4)Pan. \n(Enter 1,2,3, or 4.)");
doughType = keyboard.nextDouble();
if (doughType == 1) {
dough = "Classic Hand Tossed";
doughVolume = area * .25;
} else if (doughType == 2) {
dough = "Thin and Crispy";
doughVolume = area * .1;
} else if (doughType == 3) {
dough = "Texas Toast";
doughVolume = area * .9;
} else if (doughType == 4) {
dough = "Pan";
doughVolume = area * .5;
}
// Toppings
System.out.print("Enter the number of toppings:");
numberOfPizzaToppings = keyboard.nextDouble();
toppings = numberOfPizzaToppings;
// Base price
basePrice = area * (PIZZA_SAUCE_AND_CHEESE + PIZZA_TOPPING_PRICE * numberOfPizzaToppings)
+ PIZZA_DOUGH_PRICE * doughVolume;
// Cheesey crust
if (doughType == 2) {
cheesyOutput = " no cheesy crust";
crustCost = basePrice;
} else {
System.out.println("Would you like cheesy crust? (1) for yes (2) for no.");
cheesyCrustInput = keyboard.nextDouble();
if (cheesyCrustInput == 1 && pizzaShape == 2) {
sizeOfPizzaCrust = 2 * Math.PI * (pizzaDiamiter / 2);
crustCost = (sizeOfPizzaCrust * .02) + basePrice;
crust = "";
cheesyOutput = " cheesy crust";
} else if (cheesyCrustInput == 1 && pizzaShape == 1) {
sizeOfPizzaCrust = 2 * (pizzaLength + pizzaWidth);
crustCost = (sizeOfPizzaCrust * .02) + basePrice;
crust = "";
cheesyOutput = " cheesy crust";
} else {
crust = " NO cheesy crust";
crustCost = basePrice;
}
}
// how many pizzas
System.out.print("Enter the number of pizzas being ordered:");
numberOfPizzas = keyboard.nextDouble();
pizzasBeforeTax = crustCost * numberOfPizzas;
// tax
costOfPizzaWithTax = pizzasBeforeTax * (1 + 0.07);
// delivery fee
System.out.print("Would you like delivery? (1) for yes, (2) for no.");
deliveryWantedInput = keyboard.nextDouble();
if (deliveryWantedInput == 1) {
deliveryOutput = (int) numberOfPizzas + " pizza delivered";
if (costOfPizzaWithTax < 10) {
deliveryCharge = 3;
} else if (10 < costOfPizzaWithTax && costOfPizzaWithTax < 20) {
deliveryCharge = 2;
} else if (20 < costOfPizzaWithTax && costOfPizzaWithTax < 30) {
deliveryCharge = 1;
} else if (costOfPizzaWithTax > 30) {
deliveryCharge = 0;
}
} else {
deliveryOutput = "no delivery";
deliveryCharge = 0;
}
// display total
total = costOfPizzaWithTax + deliveryCharge;
if (pizzaShape == 1) {
System.out.print("User requested: Rectangular, " + (int) pizzaLength + "X"
+ (int) pizzaWidth + ", " + dough
+ ", " + (int) toppings + " topping(s)," + crust + cheesyOutput + ", "
+ deliveryOutput + " - Program Output:");
System.out.println("\nDetails for - Rectangular Pizza (" + pizzaLength + "\" X "
+ pizzaWidth + "\"):");
System.out.printf("Area: %.3f\n", area);
System.out.printf("Volume: %.3f\n", doughVolume);
System.out.printf("Base price: $%.2f", basePrice);
System.out.printf("\nWith Cheesy: $%.2f", crustCost);
System.out.printf("\nMulti Total: $%.2f", pizzasBeforeTax);
System.out.printf("\nWith Tax: $%.2f", costOfPizzaWithTax);
System.out.printf("\nAnd Delivery: $%.2f", total);
}
else {
System.out.print("User requested: Circular, " + (int) pizzaDiamiter + "\", "
+ dough + ", " + (int) toppings + " topping(s)," + crust + cheesyOutput
+ ", " + deliveryOutput + " - Program Output:");
System.out.println("\nDetails for - Round Pizza (" + pizzaDiamiter + "\" diameter):");
System.out.printf("Area: %.3f\n", area);
System.out.printf("Volume: %.3f\n", doughVolume);
System.out.printf("Base price: $%.2f", basePrice);
System.out.printf("\nWith Cheesy: $%.2f", crustCost);
System.out.printf("\nMulti Total: $%.2f", pizzasBeforeTax);
System.out.printf("\nWith Tax: $%.2f", costOfPizzaWithTax);
System.out.printf("\nAnd Delivery: $%.2f", total);
}
}
}

Your problem is related to scopes:
if ( condition ) {
String topping = "topping";
}
System.out.println(topping);
Will not compile. (Your code is a bit more broad, but still)
The problem here is that topping is a local variable in the if-block, once the if-block is terminated, the variable doesn't exist anymore.
You need to fix it to something like:
String topping = "default";
if ( condition ) {
topping = "topping";
}
System.out.println(topping);

Here is the error free code you need. You just need to create the methods and write your logic in it.
import java.util.Scanner;
public class pizzas {
public static void main(String[] args) {
Scanner keyboard = new Scanner( System.in );
int pizzaLength = 0;
int pizzaWidth = 0;
int pizzaShape;
double pizzaDiamiter = 0;
double pizzaToppingPrice = 0.025;
int numberOfPizzaToppings;
double pizzaSauceAndCheese = 0.036;
double pizzaDoughPrice = 0.019;
char doughType;
String dough = null;
int numberOfPizzas;
double pizzasBeforeTax;
int cheesyCrustInput;
int deliveryWantedInput;
int deliveryCharge = 0;
double doughVolume = 0;
double area = 0;
double crustCost;
int basePrice;
int costOfPizzaWithTax;
//Shape of pizza
System.out.println("What shape of pizza requested?");
System.out.println("Enter (1) for Rectange or (2) Round?");
pizzaShape = keyboard.nextLine().charAt(0);
if(pizzaShape == 1){
System.out.println("What Length?");
pizzaLength = keyboard.nextInt();
System.out.println("What Width?");
pizzaWidth = keyboard.nextInt();
area = pizzaLength * pizzaWidth;
}
else if(pizzaShape == 2){
System.out.println("What is the Diamiter?");
pizzaDiamiter = keyboard.nextInt();
area = Math.PI * (pizzaDiamiter / 2);
}
//Volume
System.out.print("What type of dough do you want? (1)Classic Hand-Tossed, (2)Thin and Crispy, (3)Texas Toast, or (4)Pan. (enter 1,2,3, or 4.");
doughType = keyboard.nextLine().charAt(0);
String Crust = "";
String deliveryOutput="";
if (doughType == 1) {
dough = "Classic Hand-Tossed";
doughVolume = area * .25;
}
else if (doughType == 2) {
dough = "Thin and Crispy";
doughVolume = area * .1;
}
else if (doughType == 3) {
dough = "Texas Toast";
doughVolume = area * .9;
}
else if (doughType == 4) {
dough = "Pan";
doughVolume = area * .5;
}
//Cheesey crust
if(doughType == 2){
}
else{
System.out.println("Would you like cheesy crust? (1) for yes (2) for no");
cheesyCrustInput = keyboard.nextInt();
if(cheesyCrustInput == 1){
crustCost = area * .02;
Crust = "";
}
else{
Crust = "NO";
}
}
//Toppings
System.out.print("Enter the number of toppings:");
numberOfPizzaToppings = keyboard.nextInt();
int toppings;
if(numberOfPizzaToppings == 0){
toppings = 0;
}
else{
toppings = numberOfPizzaToppings;
}
//Base price
basePrice = area (pizzaSauceAndCheese + (pizzaToppingPrice * numberOfPizzaToppings) + (pizzaDoughPrice * doughVolume));
//how many pizzas
System.out.print("Enter the number of pizzas being ordered:");
numberOfPizzas = keyboard.nextInt();
pizzasBeforeTax = basePrice * numberOfPizzas;
//tax
costOfPizzaWithTax = pizzasBeforeTax ( 1 + 0.07);
//delivery fee
System.out.print("Would you like delivery? (1) for yes, (2) for no.");
deliveryWantedInput = keyboard.nextInt();
if(deliveryWantedInput == 1){
deliveryOutput = numberOfPizzas + "deliverd";
if(costOfPizzaWithTax < 10){
deliveryCharge = 3;
}
if( 10 < costOfPizzaWithTax && costOfPizzaWithTax < 20 ){
deliveryCharge = 2;
}
if(20 < costOfPizzaWithTax && costOfPizzaWithTax < 30){
deliveryCharge = 1;
}
if(costOfPizzaWithTax > 30){
deliveryCharge = 0;
}
}
else{
deliveryOutput = "no delivery";
}
//display total
int total = costOfPizzaWithTax + deliveryCharge;
//System.out.println("Total Due: $" + df.format(total));
if(pizzaShape == 1){
System.out.print("User requested: Rectangular, " + pizzaWidth + "X"
+ pizzaLength + ", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println("Details for - Rectangular Pizza (" + pizzaWidth + "\" X " + pizzaLength + "\"):");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
else{
System.out.print("User requested: Circular, " + pizzaDiamiter + "\", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
}
Methods:
private static int pizzasBeforeTax(double d) {
// TODO Auto-generated method stub
return 0;
}
private static int area(double d) {
// TODO Auto-generated method stub
return 0;
}
Issues in your code:
1. You have not initialized the variables you have used.
2. You have declared the variables in if and else clause. When you are planning to re-use the variables, never initialize them inside as their scope is restricted to the block.
3. Also, you have used the same variable name toppings as String and int .

Related

While loop not breaking after user input, requiring multiple inputs before breaking

I'm having issues with my loop. I'm trying to have the user input a number selection that repeats if they select an item and exits if they input 5. However, when running it, if I select 2 items, it would require me to enter 5 twice to exit the loop.
I appreciate any help.
public static void coffee() {
double espressoP = 4.50;
double latteP = 4.50;
double cappuccinoP = 6.00;
double coldBrewP = 4.00;
int coffeeChoice = 0;
boolean exit = true;
System.out.println("=== Select Coffee: ===");
System.out.println("1. Espresso $4.50");
System.out.println("2. Latte $4.50");
System.out.println("3. Cappuccino $6.00");
System.out.println("4. Cold Brew $4.00");
System.out.println("5. Quit coffee selection.");
System.out.println("Select a coffee [Enter 1 - 5]:");
while (exit = true) {
coffeeChoice = scnr.nextInt();
if (coffeeChoice == 1) {
System.out.println("Added 1 Espresso.");
C1 += 1;
totPrice = totPrice + espressoP;
System.out.println(C1 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 2) {
System.out.println("Added 1 Latte.");
C2 += 1;
totPrice = totPrice + latteP;
System.out.println(C2 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 3) {
System.out.println("Added 1 Cappuccino.");
C3 += 1;
totPrice = totPrice + cappuccinoP;
System.out.println(C3 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 4) {
System.out.println("Added 1 Cold Brew.");
C4 += 1;
totPrice = totPrice + coldBrewP;
System.out.println(C4 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 5) {
exit = false;
break;
}
else {
System.out.println("Invalid entry. Enter a selection between 1 and 5.");
scnr.next();
}
}
Updated. Agree with comments. exit = true is a typo, break will nullify it. Reason of multiple asking for input "5" is because of recursion.

I want to find max and min values in java

I want max and min values of salary to display but i get same values for max and min. Here's my code:
import java.util.*;
class Wage {
String employee_name, skill;
int hours;
double sum;
String[] sno = {"1", "2", "3", "4"};
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
Scanner s = new Scanner(System.in);
public void getEmployeeDetails() {
System.out.println("Welcome to Use General Wage Record System");
for (String count : sno) {
if (count.equalsIgnoreCase("1")) {
System.out.print("Enter Name of Employee 1: ");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("2")) {
System.out.print("Enter Name of Employee 2:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee " + employee_name + "(Level " + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("3")) {
System.out.print("Enter Name of Employee 3:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " $" + sum);
}
}
if (count.equalsIgnoreCase("4")) {
System.out.print("Enter Name of Employee 4:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + "$ " + sum);
}
}
}
}
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
if (sum > max) {
max = sum;
System.out.println("Maximum of wage" + max + ", " + employee_name);
}
if (sum < min) {
min= sum ;
System.out.println("Minimum of Wage" + min + ", " + employee_name);
}
}
}
public class Pay {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Wage wm = new Wage();
wm.getEmployeeDetails();
wm.average();
}
In the loop of the getEmployeeDetails() method, you don't store and update the min wage, the max wage and the employee names that have these wages.
Besides, you should be more specific in the naming. For example, maxWage and minWage are more meaningful than max and min.
So, you should have maxWage, maxWageEmployeeName, minWage and minWageEmployeeName fields in the field declaration of the Wage class.
At each employee inserted in the system, you should update these values by calling a dedicated method:
public void getEmployeeDetails() {
if (count.equalsIgnoreCase("1")) {
....
updateRanking(sum, employee_name);
}
}
public void updateRanking(double actualWage, String employee_name){
if (actualWage > maxWage) {
maxWage = actualWage;
maxWageEmployeeName = employee_name;
}
else if (actualWage < minWage) {
minWage = actualWage;
minWageEmployeeName = employee_name;
}
}
Besides, your average() method called at the end of your program should only display the result and not performing comparison since you should have updated information about max, min wage and who have these as updateRanking() is called at each insertion of employee wage :
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
System.out.println("Maximum of wage" + maxWage + ", " + maxWageEmployeeName );
System.out.println("Minimum of Wage" + minWage + ", " + minWageEmployeeName );
}

Repeated Output, have to end the program manually

I am a beginner and not tried the following program which is giving me repeated output.. I have to end the program manually in eclipse. Not able to figure out the problem. Please advice. Any other tips are welcome.
import java.util.Scanner;
public class Sales_Amount {
public static void main(String[] args) {
final double Base_Salary = 25000;
double Commission = 0;
double Total_Salary;
double X;
double Y;
Scanner input = new Scanner(System. in );
System.out.print("Enter Sales Amount: ");
double Sales = input.nextDouble();
while (Commission < 25001) {
if (Sales <= 5000); {
Total_Salary = Base_Salary + (0.08 * Sales);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 5000 && Sales < 10001); {
X = Sales - 5000;
Total_Salary = Base_Salary + (0.08 * 5000) + (0.10 * X);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 10001); {
Y = Sales - 10000;
Total_Salary = Base_Salary + (.08 * 5000) + (.10 * 10000) + (.12 * Y);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
}
}
}
Add commission++ before the end of the loop.

Unsure about the best loop to use

public static void main(String[] args) {
Scanner keybNum = new Scanner(System.in);
Scanner keybStr = new Scanner(System.in);
boolean yn = false;
//Start of program
System.out.println("Welcome to The Currency Exchange Converter");
System.out.print("Are you an Account Holder (y or n)? ");
String AccHolder = keybStr.next();
boolean blnYN = true;
//validation of y/n answer
while (blnYN) {
if (AccHolder.equalsIgnoreCase("y")) {
yn = true;
blnYN = false;
break;
}//if
else if (AccHolder.equalsIgnoreCase("n")) {
yn = false;
blnYN = false;
break;
}//else if
else {
System.out.println("Invalid value entered. Choose either y/n.");
AccHolder = keybStr.next();
}//else
}//while
//Start of menu choices
System.out.println("Please choose from the following menu.");
System.out.println("\n1: Exchange another currency for Sterling");
System.out.println("2: Buy another currency from us");
System.out.println("0: Exit");
System.out.print("Which option? ");
int MenuChoice = keybNum.nextInt();
//Exchange Variables (First option)
double Euro = 1.37;
double USAD = 1.81;
double JapYen = 190.00;
double Zloty = 5.88;
//Buy Variables (Second Option)
double EuroB = 1.21;
double USADB = 1.61;
double JapYenB = 163.00;
double ZlotyB = 4.89;
//First menu choice screen
if (MenuChoice == 1) {
System.out.println("Which of the following currencies do you wish to exchange into sterling?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
//Exchange amount calculator
System.out.print("Enter the amount you wish to exchange of " + CurChoice + ": ");
double ExcAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = ExcAmount / Euro;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("USD")) {
result = ExcAmount / USAD;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("JPY")) {
result = ExcAmount / JapYen;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("PLN")) {
result = ExcAmount / Zloty;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else {
System.out.println("");
}
DecimalFormat df = new DecimalFormat("#.##");
double commission = 0;
if (ExcAmount < 1000) {
commission = result * 0.02;
} else {
commission = result * 0.01;
}
String stringToPrint = "";
if (!yn) {
stringToPrint = "Commission\t=£" + df.format(commission);
} else {
stringToPrint = "Commission \t= Not charged";
}
System.out.println(stringToPrint);
double netPayment = result - commission;
System.out.println("Total\t\t=£" + df.format(netPayment));
}//if
//Start of second option
else if (MenuChoice == 2) {
System.out.println("Which of the following currencies do you wish to buy from us?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
System.out.print("Enter the amount you wish to buy in £ of " + CurChoice + ": £");
double BuyAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = BuyAmount * EuroB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("USD")) {
result = BuyAmount * USADB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("JPY")) {
result = BuyAmount * JapYenB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("PLN")) {
result = BuyAmount * ZlotyB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else {
System.out.println("");
}
DecimalFormat df = new DecimalFormat("#.##");
double commission = 0;
if (BuyAmount < 1000) {
commission = result * 0.02;
} else if (BuyAmount >= 1000) {
commission = result * 0.01;
} else {
}
String stringToPrint = "";
if (!yn) {
stringToPrint = "Commission\t= " + df.format(commission) + " " + CurChoice;
} else {
stringToPrint = "Commission \t= Not charged";
}
System.out.println(stringToPrint);
double netPayment = result - commission;
System.out.println("Total\t\t= " + df.format(netPayment) + " " + CurChoice);
}//else if
//Action if the user selects 0 to close the system.
else {
System.out.println("Thank you for visiting.");
}//else
}//main
So I'm not sure about the best loop to use on my program. I want the program to repeat if the user inputted either 1 or 2 at the start of the program. The programs a simple currency exchange converter. Any help?
Ideally, you have a program logic according to:
int choice = 0;
while( (choice = readChoice()) != 0 ){
// process according to choice
// ...
}
Wrap the first menu in a static method:
public static int readChoice()
And add the while statement.
(All of your code would benefit from being structured in methods. It's getting unwieldy as you are adding new features. Remember - I have seen an older version)
Consider a do { } while(...); loop. it should be do {...} while (MenuChoice == 1 || MenuChoice == 2); Make sure MenuChoice is always given a value before reaching the while statement. The do while should surround starting from the line //Start of menu choices and to the bottom.
Also, consider a switch case for the MenuChoice

Hanging token from user input is not allowing me to proceed in my program

My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);

Categories

Resources