I would like this program below to capture user input (first product name, then costs), and then output to the console, and ask the user if they would like anything else, and if they do, it will do it again and output the next product and costs.
If the user replies with no, then I want it to output a list of the items by number and name, and then the total costs of how every many items were requested, and then a total overall cost.
Here is my code so far; I want to understand how to get the total overall costs and list each item. I feel like I am very close.
public static void main(String[] args) {
/////////Initialize everything here/////////
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR " + items + " ITEMS: " + "\nShipping (flat fee): " + shipping + "\nSum of Items: ");
}}
You need a list to hold item names and one temporary variable to hold sum of prices. I think below code will help you.
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
List<String> orderItems = new ArrayList<>();
double totalPrice=0;
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
orderItems.add(nameProd);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
totalPrice+=totAmt;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR ITEMS: " + orderItems + "\nShipping (flat fee): " + shipping + "\nSum of Items: "+totalPrice);
}
Related
All of my main methods take place in this class:
package wk2individual;
import java.util.Scanner;
public class Wk2Individual {
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
SalesPerson sP = new SalesPerson();
//System greeting
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Employee Annual Pay calculator!");
//user input
System.out.println("Please enter the name of the first sales employee:");
sP.salesPerson1 = sc.next();
System.out.println ("Please enter " + sP.salesPerson1 + "'s total sales for the year:");
aPC.totalSales1 = sc.nextDouble();
//begin outputs
if (aPC.totalSales1 >= 112000 && aPC.totalSales1 < 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total1() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total2()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales1 >= 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total3() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total4()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales1 < 112000) {
System.out.println(sP.salesPerson1 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson1 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//begin the inputs for the second salesperson
System.out.println("Now let's get the name of the second sales employee:");
sP.salesPerson2 = sc.next();
System.out.println("Please enter " + sP.salesPerson2 + "'s total sales for the year:");
aPC.totalSales2 = sc.nextDouble();
//begin outputs
if (aPC.totalSales2 >= 112000 && aPC.totalSales2 < 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total5() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total6()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales2 >= 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total7() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total8()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales2 < 112000) {
System.out.println(sP.salesPerson2 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson2 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//This is where I am trying to print the array created in the SalesPerson class
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
System.out.print(n);
}
}
I created the AnnualPayCalculator class to hold the totals and calculations:
package wk2individual;
public class AnnualPayCalculator
{
double totalSales1, totalSales2, employee1TotalPay, employee2TotalPay;
double fixedSalary = 75000.00;
final double commissionRate = .25;
double salesTarget = 140000;
double accelerationFactor = .3125;
double total1(){
double incentiveCommission = totalSales1 * commissionRate;
return incentiveCommission;
}
double total2(){
double employee1TotalPay = total1() + fixedSalary;
return employee1TotalPay;
}
double total3(){
double targetCommission = totalSales1 * accelerationFactor;
return targetCommission;
}
double total4(){
double employee1TotalPay = total3() + fixedSalary;
return employee1TotalPay;
}
double total5(){
double incentiveCommission = totalSales2 * commissionRate;
return incentiveCommission;
}
double total6(){
double employee2TotalPay = total5() + fixedSalary;
return employee2TotalPay;
}
double total7(){
double targetCommission = totalSales2 * accelerationFactor;
return targetCommission;
}
double total8(){
double employee2TotalPay = total7() + fixedSalary;
return employee2TotalPay;
}
}
Then I created this SalesPerson class in which holds my array:
package wk2individual;
public class SalesPerson {
String salesPerson1, salesPerson2;
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
};
private static void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
In the first class I am able to print the totals of the calculations defined in the AnnualPayCalculator class. How can I print the array in the first class?
You probably don't want 2 main methods. When you create an object of SalesPerson in Wk2Individual, the 2d array sales is not being declared because static methods and variables are not part of instances/objects of classes. So what you might want to do is make a non-static method in SalesPerson like this;
public class SalesPerson {
String salesPerson1, salesPerson2;
public void createSales(AnnualPayCalculator aPC) {
// you don't need to create aPC
// AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
}
}
Also, you are probably trying to use the values from the aPC object in the Wk2Individual class. But you are creating a new instance of the object instead. So you should pass the old aPC object from Wk2Individual class like this:
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
sP.createSales(aPC);
This will send the aPC object with all the calculated values to the createSales() of SalesPerson class where your 2d array will be created.
Now you need to print this. To do that create a print method in the SalesPerson class:
private void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
But you cannot print an array like that. So do this:
System.out.println(Arrays.toString(n));
In AnnualPayCalculator class you have several methods which use the global variables: employee1TotalPay and employee2TotalPay. For example, the method total2(). In these methods, you are creating yet another variable with the same name. In total2() you are creating employee1TotalPay which shadows the global variable employee1TotalPay. It means that if inside that method you use employee1TotalPay anywhere, it will use the local employee1TotalPay variable (the one you created inside the method). To use the global variable either remove the declaration of the local variable:
employee1TotalPay = total1() + fixedSalary;
or use the this keyword to access the global variables:
this.employee1TotalPay = total1() + fixedSalary;
I just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}
So I can't get the variables to be divisible, I need to be able to do this, otherwise I don't know of a way to finish building the lock that I want to build.
It uses 20 inputted numbers, and then arranges them into a Algebra2/calculus system of equations, and then solves for the "s", "a", "f", and "e" it starts by removing "e" from the equation by substituting.
I would greatly appreciate help, I'm open to ideas as well, because sofar I have 25 of these to build, and this is only 1/3 of the first one.
In short, how do I divide variables?
import java.util.Scanner;
public class Lock
{
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
String num_a;
System.out.print("Enter the first number: ");
num_a = user_input.next();
String num_b;
System.out.print("Enter the second number: ");
num_b = user_input.next();
String num_c;
System.out.print("Enter the third number: ");
num_c = user_input.next();
String num_d;
System.out.print("Enter the fourth number: ");
num_d = user_input.next();
String num_e;
System.out.print("Enter the fifth number: ");
num_e = user_input.next();
String num_f;
System.out.print("Enter the sixth number: ");
num_f = user_input.next();
String num_g;
System.out.print("Enter the seventh number: ");
num_g = user_input.next();
String num_h;
System.out.print("Enter the eigth number: ");
num_h = user_input.next();
String num_i;
System.out.print("Enter the ninth number: ");
num_i = user_input.next();
String num_j;
System.out.print("Enter the tenth number: ");
num_j = user_input.next();
String num_k;
System.out.print("Enter the eleventh number: ");
num_k = user_input.next();
String num_l;
System.out.print("Enter the twetlth number: ");
num_l = user_input.next();
String num_m;
System.out.print("Enter the thirteenth number: ");
num_m = user_input.next();
String num_n;
System.out.print("Enter the fourteenth number: ");
num_n = user_input.next();
String num_o;
System.out.print("Enter the fifteenth number: ");
num_o = user_input.next();
String num_p;
System.out.print("Enter the sixteenth number: ");
num_p = user_input.next();
String num_q;
System.out.print("Enter the seventeenth number: ");
num_q = user_input.next();
String num_r;
System.out.print("Enter the eighteenth number: ");
num_r = user_input.next();
String num_s;
System.out.print("Enter the nineteenth number: ");
num_s = user_input.next();
String num_t;
System.out.print("Enter the twentieth number: ");
num_t = user_input.next();
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "e = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "e = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "e = " + num_o);
System.out.println(num_p + "s + " + num_q + "a + " + num_r + "f + " + num_s + "e = " + num_t);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_o);
// THIS creates the fourth equation items/order to be substituted into the other first three equations.
int t = num_t;
int s = num_s;
int num_ts = (t / s);
num_ts =
num_ps = (num_p / num_s);
num_qs = (num_q / num_s);
num_rs = (num_r / num_s);
// THIS is the Fourth equation being substituted into the First Equation
num_dts = (num_d * num_ts);
num_dps = (num_d * num_ps);
num_dqs = (num_d * num_qs);
num_drs = (num_d * num_rs);
// THIS is the Fourth equation being substituted into the Second Equation
num_its = (num_i * num_ts);
num_ips = (num_i * num_ps);
num_iqs = (num_i * num_qs);
num_irs = (num_i * num_rs);
// THIS is the fourth equation being substituted into the Third Equation
num_nts = (num_n * num_ts);
num_nps = (num_n * num_ps);
num_nqs = (num_n * num_qs);
num_nrs = (num_n * num_rs);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_dts + " " + num_dps + "s + " + num_dqs + "a " + num_drs + "f = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_its + " " + num_ips + "s + " + num_iqs + "a " + num_irs + "f = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_nts + " " + num_nps + "s + " + num_nqs + "a " + num_nrs + "f = " + num_o);
}
}
You can't add, subtract, divide, or multiply String variables. You have to make your variables into ints in order to do that. Also, you can use an array to hold your variables, since there is so many of them.
String, Integer, Float, are not the same types. you can't apply operators like / or * on String for instance. + is special because it has a definition for String, which means concatenate.
Since you need to do some operations on the user inputs, you can read them directly as int:
System.out.print("Enter the first number: ");
int num_a = user_input.nextInt();
System.out.print("Enter the second number: ");
int num_b = user_input.nextInt();
Then you can do
int num_ab = a / b;
Note that if a < b, then num_ab will be 0, since this is an integer. You may want to do something like
float num_ab = (float)a / b;
Now, this code is quite tedious. If you accept to handle indices instead of letters for the variables, you can initialise them in a loop, e.g.
Scanner in = new Scanner(System.in);
int[] numbers = new int[20];
int index = 0;
while (index < numbers.length) {
System.out.println("Enter the "+(index+1)+"th number");
int n = in.nextInt();
numbers[index] = n;
index++;
}
System.out.println(Arrays.toString(numbers));
And use the array of numbers
// arrays start at 0
int num_ab = numbers[0] / numbers[1];
And if you want to be able to access the variables through names, you can define constants
static final int a = 0;
static final int b = 1;
static final int c = 2;
//...
int num_ab = numbers[a] / numbers[b];
But in your case, it may be handy to store initial variables and computed ones in some place where you can retrieve them for further computations:
// the store for all the variables and their value
static Map<String, Integer> vars = new HashMap<>();
// the function to read in the store
static Integer var(String name) {
return vars.get(name);
}
The store is initialised by a loop:
Scanner in = new Scanner(System.in);
// The 20 variables...
String alpha = "abcdefghijklmnopqrst";
for (char c : alpha.toCharArray()) {
String varName = String.valueOf(c);
System.out.println("Enter the value for "+ varName);
int n = in.nextInt();
vars.put(varName, n);
}
System.out.println(vars.toString());
int num_ab = var("a")/var("b");
// Store ab for further computation
vars.put("ab", num_ab);
System.out.println("ab is " + var("ab");
I'm working on a little Java program that outputs a receipt to email students who registered for an AP exam at my school. The code looks like this.
// Create email text body for student who registered for an AP exam.
import java.util.Scanner;
class EmailText {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String first_name;
String email;
int numTests;
char ch;
char choice;
int cost;
System.out.print("Enter student first name: ");
first_name = input.next();
System.out.print("Enter student email: ");
email = input.next();
System.out.print("Enter number of tests ordered (1-9): ");
numTests = input.nextInt();
if(numTests < 10) {
System.out.print("Did student qualify for fee waiver (y/n)? ");
ch = input.next().charAt(0);
if(ch == 'y') {
cost = 5;
int total = numTests * cost;
System.out.println("** COPY/PASTE THIS DRAFT **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.\n");
System.out.println("Because you stated that you qualified for a fee waiver, " +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the College Counseling Office ASAP.\nThank you.\n");
}
else if(ch == 'n') {
cost = 89;
int total = numTests * cost;
System.out.println("** Copy/Paste this Draft **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.");
System.out.println("Because you stated that you qualified for a fee waiver, " +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the College Counseling Office ASAP.\nThank you.\n");
}
}
else {
System.out.println("Please start again.");
return;
}
}
}
The problem I have with this is that I am repeating the same System.out.println() body in the else and if blocks. Instead, what I would like to do is to perhaps create a method that could be called in each block.
If possible, how can I accomplish this?
If this is what you mean, then you need to read up on basic Java, I've added your method in the code sample, please read this link to understand more about methods: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
See Peter's answer for more information too!
// Create email text body for student who registered for an AP exam.
import java.util.Scanner;
class EmailText {
public static void main(String args[]) {
int numTests, cost;
String email, first_name;
char ch;
Scanner input = new Scanner(System.in);
System.out.print("Enter student first name: ");
first_name = input.next();
System.out.print("Enter student email: ");
email = input.next();
System.out.print("Enter number of tests ordered (1-9): ");
numTests = input.nextInt();
if(numTests < 10) {
System.out.print("Did student qualify for fee waiver (y/n)? ");
ch = input.next().charAt(0);
if(ch == 'y') {
cost = 5;
PrintStuff(numTests, cost, email, first_name, "qualified for a fee waiver, ");
}
else if(ch == 'n') {
cost = 89;
PrintStuff(numTests, cost, email, first_name, "did not qualify for a fee waiver, ");
} else {
System.out.println("Please start again.");
}
}
}
public static void PrintStuff(int numTests, int cost, String email, String first_name, String fw_status) {
int total = numTests * cost;
System.out.println("** COPY/PASTE THIS DRAFT **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.\n");
System.out.println("Because you stated that you " + fw_status +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the Student Store ASAP.\nThank you.\n");
}
}
No need for a method, just some DRY refactoring:
if(ch == 'y' || ch == 'n') {
cost = ch == 'y' ? 5 : 89;
int total = numTests * cost;
System.out.println("** COPY/PASTE THIS DRAFT **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.\n");
System.out.println("Because you stated that you qualified for a fee waiver, " +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the College Counseling Office ASAP.\nThank you.\n");
} else {
System.out.println("Please start again.");
return;
}
Create a method something like this:
private String createOutput(int cost, String email, String first_name...)
{
StringBuffer outputBuffer = new StringBuffer();
outputBuffer.append("** Copy/Paste this Draft **\n");
outputBuffer.append("To: " + email + "\n");
outputBuffer.append("Subject: 2014 AP Test Receipt for " + first_name + "\n");
outputBuffer.append("\n");
...
return outputBuffer.toString();
}
Then your IF statement will look like this:
if(ch == 'y') {
cost = 5;
int total = numTests * cost;
System.out.println(createOutput(cost, email, first_name, ...);
}
else if (ch == 'n') {
cost = 89;
int total = numTests * cost;
System.out.println(createOutput(cost, email, first_name, ...);
}
You can create another method outside the main that prints your repeated System.out.println
and this method may contain parameters like this
public void print(total){
System.out.println("** Copy/Paste this Draft **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.");
System.out.println("Because you stated that you qualified for a fee waiver, " +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the College Counseling Office ASAP.\nThank you.\n");
}
and in your main you can access this method or put it inside your conditions like
if(ch == 'y') {
cost = 5;
int total = numTests * cost;
print(total);
}
You accomplish this by adding parameters to this method. Everything
which is not to be printed exactly the same between one if/else if block
and another else if block, you make a parameter of the method. Then from
the different blocks you call the same method but you pass different values
for the parameters.
import static java.lang.System.out;
Will allow you to simply refer to that code, although is generally considered a bad practice and is only for one-off programs.
Simply saving a reference to System.out will save you that part
PrintStream out = System.out;
out.println( "hello" );
Alternatively write yourself a nice shorthand method
public static void print(String s){
System.out.println(s);
}
You'll have to write overloads for int, double, etc. or alternatively you can use string concatenation
int x = 10;
print(x + "");
Or did you mean just for your big block of code there? In that case...
public void printBlock(String email, String first_name, int numTests, int cost, int total){
System.out.println("** COPY/PASTE THIS DRAFT **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.\n");
System.out.println("Because you stated that you qualified for a fee waiver, " +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the College Counseling Office ASAP.\nThank you.\n");
}
Now just call
if(thing){
printBlock("email","firstname",1,10,10);
}
else{
printBlock("email","othername",2,20,40);
}
Or whatever.
I'm trying to write this compounding interest program with a do while loop at the end and I cannot figure out how to print out the final amount.
Here is the code I have so far :
public static void main(String[] args) {
double amount;
double rate;
double year;
System.out.println("This program, with user input, computes interest.\n" +
"It allows for multiple computations.\n" +
"User will input initial cost, interest rate and number of years.");
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the initial cost?");
amount = keyboard.nextDouble();
System.out.println("What is the interest rate?");
rate = keyboard.nextDouble();
rate = rate/100;
System.out.println("How many years?");
year = keyboard.nextInt();
for (int x = 1; x < year; x++){
amount = amount * Math.pow(1.0 + rate, year);
}
System.out.println("For " + year + " years an initial " + amount + " cost compounded at a rate of " + rate + " will grow to " + amount);
String go = "n";
do{
System.out.println("Continue Y/N");
go = keyboard.nextLine();
}while (go.equals("Y") || go.equals("y"));
}
}
The trouble is, amount = amount * Math.pow(1.0 + rate, year);. You're overwriting the original amount with the calculated amount. You need a separate value to hold the calculated value while still holding the original value.
So:
double finalAmount = amount * Math.pow(1.0 + rate, year);
Then in your output:
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " + finalAmount);
EDIT: Alternatively, you can save a line, a variable, and just do the calculation inline, as such:
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " +
(amount * Math.pow(1.0 + rate, year)));