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
Related
im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow;
public class Calculator extends DIYWindow {
public Calculator() {
// getting number one
double number1 = promptForDouble("Enter a number");
//getting number2
int number2 = promptForInt("Enter an integer");
//getting what to do with operation
print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide");
String operation = input();
//declaring variable here so the same one can be used
double answer = 0;
switch(operation) {
case "add":
answer = number1 + number2;
print(number1 + " + " + number2 + " = " + answer);
break;
case "subtract":
answer = number1 - number2;
print(number1 + " - " + number2 + " = " + answer);
break;
case "multiply":
answer = number1 * number2;
print(number1 + " * " + number2 + " = " + answer);
break;
case "divide":
try {
answer = number1 / number2;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(number1 + " / " + number2 + " = " + answer);
break;
}
double double1 = promptForDouble("Enter a number");
double double2 = promptForDouble("Enter another number");
double double3 = promptForDouble("Enter one last number");
print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide");
String operation2 = input();
double answer2 = 0;
switch(operation2) {
case "add":
answer2 = double1 + double2 + double3;
print(double1 + " + " + double2 + " + " + double3 + " = " + answer2);
break;
case "subtract":
answer2 = double1 - double2 - double3;
print(double1 + " - " + double2 + " - " + double3 + " = " + answer2);
break;
case "multiply":
answer2 = double1 * double2 * double3;
print(double1 + " * " + double2 + " * " + double3 + " = " + answer2);
break;
case "divide":
try {
answer2 = double1 / double2 / double3;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(double1 + " / " + double2 + " / " + double3 + " = " + answer2);
break;
}
want it to loop after the code on top
}
private double promptForDouble(String prompt) {
double number1 = 0;
print(prompt);
String number = input();
try {
number1 = Double.parseDouble(number);
}
catch(NumberFormatException e){
print("That is not a number. Please enter a number.");
number1 = promptForDouble(prompt);
}
return number1;
}
private int promptForInt(String prompt) {
int number2 = 0;
print(prompt);
String number = input();
try {
number2 = Integer.parseInt(number); }
catch(NumberFormatException e) {
print("That is not an integer. Enter an integer.");
number2 = promptForInt(prompt); }
return number2;
}
public static void main(String[] args) {
new Calculator();
}
}
Put this in your main method:
while (true)
{
Thread.sleep(1000); // optional, make some deplay for more nature
new Calculator();
}
Or you can wrap all body blocks of the constructor inside the above while statement.
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 .
For my current programming project I am supposed to format my testOne & testTwo like "000". While the average is supposed to be "000.0". I have used DecimalFormat to no avail. Furthermore for my letterGradeArray the letter won't display even though the letter grade is in the actual array. Here is my code:
import java.util.Scanner;
//import java.text.NumberFormat;
import java.text.DecimalFormat;
public class GradeArray
{
#SuppressWarnings({ "unused", "resource" })
public static void main(String[] args)
{
//Setup all the variables
Scanner scan = new Scanner(System.in);
int[] testOne = new int[4]; // Students’ test one grades
int[] testTwo = new int[4]; // Students’ test two grades
double[] average = new double[4]; // Students’ average grades
double z = 002.00;
char letterGrade = 0;
char[] letterGradeArray = new char[4];
DecimalFormat fmt1 = new DecimalFormat("000");
DecimalFormat fmt2 = new DecimalFormat("000.0");
//Begin asking for scores
System.out.println("For test 1,");
for (int i=0;i<testOne.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testOne[i] = scan.nextInt();
fmt1.format(testOne[i]);
}
System.out.println("\nFor test 2,");
for (int i=0;i<testTwo.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testTwo[i] = scan.nextInt();
fmt1.format(testTwo[i]);
}
//Compute average
for(int i=0;i<average.length;i++)
{
{
average[i] = (testOne[i]+testTwo[i])/z;
fmt2.format(average[i]);
}
}
//Compute letter grade
for(int i=0;i<average.length;i++)
{
if (average[i]>= 90 )
{
letterGrade = 'A';
} else if (average[i] >= 80) {
letterGrade = 'B';
} else if (average[i] >= 70) {
letterGrade = 'C';
} else if (average[i] >= 60) {
letterGrade = 'D';
} else {
letterGrade = 'F';
}
//Put the letterGrade into the letterGradeArray
for(int x=0;i<letterGradeArray[x];x++)
{
letterGradeArray[x]=letterGrade;
}
}
//Print it out
System.out.println("Test 1 Test 2 Average Grade");
System.out.println("______ ______ _______ _____");
System.out.println(testOne[0] + " " + testTwo[0] + " " + average[0] +" " + letterGradeArray[0]);
System.out.println(testOne[1] + " " + testTwo[1] + " " + average[1] +" " + letterGradeArray[1]);
System.out.println(testOne[2] + " " + testTwo[2] + " " + average[2] +" " + letterGradeArray[2]);
System.out.println(testOne[3] + " " + testTwo[3] + " " + average[3] +" " + letterGradeArray[3]);
}
}
If anyone has any ideas on how to make this code cleaner do tell me, I feel with all the fors it is clunky.
You are calling fmt1.format(testOne[i]); but you are not doing anything with the result. Calling format returns a String, it does not affect the thing being passed as a parameter, so when you later print testOne[0] etc. you are printing the plain, original, values.
If you want the formatted values you will have to assign the return of .format() to something, keep it around, and print it instead of the original integer values. For example, patterned after how the rest of your code works...
String[] formattedOne = new String[4];
// ... later
formattedOne[i] = fmt1.format(testOne[i]);
// ... still later
System.out.println(formattedOne[0] + " " ..........
I cannot get the variable adjustedCharge to print out (the text is printed but not the value) I have tried to trace but still cannot get it to print properly. No errors are present either.
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
//Declare scanner
Scanner input = new Scanner(System.in);
//Prompt for information
System.out.print("Customer's name:");
String name = input.nextLine();
System.out.print("Customer's address:");
String address = input.nextLine();
System.out.print("Customer's phone number:");
String phone = input.nextLine();
System.out.print("Customer's licence number:");
String licence = input.nextLine();
System.out.print("Customer's credit card number:");
String ccard = input.nextLine();
System.out.print("Credit card expiry date (MM/YYYY):");
String expiry = input.nextLine();
System.out.print("Hire length (in days):");
int hire = Integer.parseInt(input.nextLine());
System.out.print("Make/Model:");
String model = input.nextLine();
System.out.print("Registration of car:");
String rego = input.nextLine();
System.out.print("Hire rate (per day) Either S, M, L:");
char inputRate = input.nextLine().charAt(0);
System.out.print("Total days hired out:");
int totalDays = Integer.parseInt(input.nextLine());
//
double dtotalDays = totalDays;
double surcharge = dtotalDays - hire;
//Daily hire rate / Stage 2
double rate = 0;
if (inputRate == 'S' || inputRate == 's'){
rate = (char) 80.0;
}
if (inputRate == 'M' || inputRate == 'm'){
rate= 110.0;
}
if (inputRate == 'L' || inputRate == 'l'){
rate= 140.0;
}
//Calculate late fees
double penalty = rate * (surcharge * 2);
//Start Stage 3
double dCost=0;
double tCost=0;
StringBuilder dDetail = new StringBuilder("The damage Details are:" + "\n");
StringBuilder tDetail = new StringBuilder("The traffic fines are:" + "\n");
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("<<<Enter one of the following commands:>>>");
System.out.println("A - Damage Repair");
System.out.println("B - Traffic Infringement");
System.out.println("X - Exit Menu");
String schoiceEntry = input.next();
char choiceEntry = schoiceEntry.charAt(0);
//Integer.parseInt(input.nextLine());
double damageCost = 0;
switch (choiceEntry){
case 'A':
case 'a':
input.nextLine();
System.out.println("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.println("Enter the damage cost:");
damageCost = input.nextInt();
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append("-" + damageDetail + "\n");
dCost = dCost + damageCost;
System.out.println("----------------------------------");
break;
case 'B':
case 'b':
input.nextLine();
System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.println("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append("-" + trafficDetail + "\n");
tCost = tCost + trafficCost;
System.out.println("----------------------------------");
break;
case 'X':
case 'x':
quit = true;
System.out.print("***Menu entry has been terminated***" + "\n");
//System.out.printf("Total traffic cost is: %75s\n", "$" + tCost + "\n");
//System.out.printf("Total Damage cost is: %77s\n", "$" + dCost + "\n");
//System.out.printf(tDetail + "\n");
//System.out.print(dDetail + "\n");
break;
default:
System.out.print("Please enter either a valid menu selection (A, B, or X):" + "\n");
break;
}
}
double dhire = hire;
double charge = dhire*rate;
double adjustedCharge = charge + penalty;
//Print summary
System.out.println("---------------------------------------------"+
"------------------------------------------------------\n" +
"***CUSTOMER DETAILS:***\n");
System.out.printf("Name: %93s\n", name);
System.out.printf("Address: %90s\n", address);
System.out.printf("Phone Number: %85s\n", phone);
System.out.printf("Licence Number: %83s\n", licence);
System.out.printf("Credit Card Number: %79s\n", ccard);
System.out.printf("Credit Card Expiry: %79s\n", expiry);
System.out.println( "\n***CAR HIRE DETAILS:***\n");
System.out.printf("Make/Model: %87s\n", model);
System.out.printf("Registration Number: %78s\n", rego);
System.out.printf("Hire Length (days): %79s\n", model);
System.out.printf("Daily Hire Rate: %82s\n", rate);
System.out.printf("Basic Hire Charge: %80s\n\n", charge);
System.out.printf("Days hired: %87s\n", totalDays);
if (totalDays == hire){
System.out.printf("Late Return Surcharge: %76s\n", "$0.00");
}
if (totalDays > hire){
System.out.printf("Late Return Surcharge: %76s\n", + penalty);
}
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");
System.out.print(dDetail + "\n");
System.out.printf("Total damage cost is: %78" + "s\n", "$" + dCost + "\n");
System.out.printf(tDetail + "\n");
System.out.printf("Total traffic fines incurred: %70s\n", "$" + tCost + "\n");
System.out.printf("Final hire charge: %79s\n", "$" + (adjustedCharge + dCost + tCost));
}
}
I just changed the way you printed out the adjustedCharge so you can still use printf
System.out.printf("Adjusted Hire Charge: %77s","$");
System.out.printf("%.1f",adjustedCharge);
System.out.printf("\n");
With printf you need to format the value you're printing and in this case, because you're trying to print a double, you'll need to format it with %f
I also noticed that my previous answer messed up the spacing you had for the rest of your output. So here's the fixed solution! Just change up the spacing to however you'd like
Or you can
use
Pass two arguments to printf
System.out.printf("Adjusted Hire Charge: %77s\n", "$" + adjustedCharge + "\n")
instead of
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");
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);