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.
Related
This question already has answers here:
Using variables outside of an if-statement
(2 answers)
Closed 12 months ago.
For context I'm a first year It student. We are tasked to create a concept program for a payment system for our final project. We decided to do a payroll program.
Here is a snippet of my code using JOptionFrame and JOptionPane
//Wages based on Job Position
if (JobPositionComboBox.getSelectedItem().equals("Project Manager")){
double wage = 350.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
else if (JobPositionComboBox.getSelectedItem().equals("System Analyst")){
double wage = 250.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
else if (JobPositionComboBox.getSelectedItem().equals("System Developer")){
double wage = 320.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
else if (JobPositionComboBox.getSelectedItem().equals("Quality Assurance")){
double wage = 220.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
jTextArea1.append("Payment Option : " + PaymentOptionComboBox.getSelectedItem() + "\n");
jTextArea1.append("--------------------------------------------");
//Payment option information prompts
if (PaymentOptionComboBox.getSelectedItem().equals("Bank Account")){
String ban = JOptionPane.showInputDialog(null, "Please enter your Bank Account Number", "Payment Option",JOptionPane.PLAIN_MESSAGE);
int BAN = Integer.parseInt(ban);
JOptionPane.showMessageDialog(null, "Transaction Information : " +
"\nName : " + NameTextField.getText() +
"\nBank Account Number : " + BAN + //I can't call on the wage inside the if statements, it just shows an error.
"\nPayment Amount : " + df.format(hour * wage) +
"\nPlease Confirm your information","Bank Account", JOptionPane.PLAIN_MESSAGE);
ImageIcon BDO = new ImageIcon(SystemFrame.class.getResource("BDO.png"));
JOptionPane.showMessageDialog(null,"Transaction Complete" +
"\nThank you for choosing our bank","Bank Account",JOptionPane.PLAIN_MESSAGE,BDO);
}
Since the number assigned to the wage variable is dependent on the job position, I have to call it from within the if statements for the computation to be accurate. Does anybody have a solution?
Please try the below and see if it works.
double wage; //declaring outside if block as a class variable/member
//Wages based on Job Position
if (JobPositionComboBox.getSelectedItem().equals("Project Manager")){
wage = 350.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
else if (JobPositionComboBox.getSelectedItem().equals("System Analyst")){
wage = 250.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
else if (JobPositionComboBox.getSelectedItem().equals("System Developer")){
wage = 320.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
else if (JobPositionComboBox.getSelectedItem().equals("Quality Assurance")){
wage = 220.f;
jTextArea1.append("Total Salary this month : " + df.format(hour * wage) + "\n");
}
jTextArea1.append("Payment Option : " + PaymentOptionComboBox.getSelectedItem() + "\n");
jTextArea1.append("--------------------------------------------");
//Payment option information prompts
if (PaymentOptionComboBox.getSelectedItem().equals("Bank Account")){
String ban = JOptionPane.showInputDialog(null, "Please enter your Bank Account Number", "Payment Option",JOptionPane.PLAIN_MESSAGE);
int BAN = Integer.parseInt(ban);
JOptionPane.showMessageDialog(null, "Transaction Information : " +
"\nName : " + NameTextField.getText() +
"\nBank Account Number : " + BAN + //I can't call on the wage inside the if statements, it just shows an error.
"\nPayment Amount : " + df.format(hour * wage) +
"\nPlease Confirm your information","Bank Account", JOptionPane.PLAIN_MESSAGE);
ImageIcon BDO = new ImageIcon(SystemFrame.class.getResource("BDO.png"));
JOptionPane.showMessageDialog(null,"Transaction Complete" +
"\nThank you for choosing our bank","Bank Account",JOptionPane.PLAIN_MESSAGE,BDO);
}
The problem with your existing code is variable scoping. You are trying to access the variable outside it's scope. Hence the error. You can read more about it here or here
I have made a dice roll game and i'm trying to increase your "cash" by whatever the inputted bet is when you win and remove it when you lose.
import java.util.*;
import javax.swing.JOptionPane;
public class Joption10 {
public static void main(String[] args) {
Random randomNumber = new Random();
//Variables
String name, bet;
int num1, num2;
int cash = 100;
int convertbet;
name = JOptionPane.showInputDialog(null, "Enter Your First Name");
JOptionPane.showMessageDialog(null, "Greetings " + name + ", welcome to roll the dice!" +"\n\nYou will start with " + cash + " euros in your wallet!" + "\n\nThe game ends when you are broke, or when you have doubled your money to 200 euros." + "\n\nGood Luck!");
while (cash > 0 && cash < 200) {
//Generate random numbers for player and dealer
num1 = randomNumber.nextInt(10) + 1; //player
num2 = randomNumber.nextInt(10) + 1; //dealer
bet = JOptionPane.showInputDialog(null, "Place your bet (1 - 100): ");
convertbet = Integer.parseInt(bet);
//Rolling
JOptionPane.showMessageDialog(null, "Rolling the dice...");
if (num2 > num1) {
JOptionPane.showMessageDialog(null, "You Win!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
cash + 10
} else if (num2 < num1) {
JOptionPane.showMessageDialog(null, "You Lose!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
} else {
JOptionPane.showMessageDialog(null, "No Winner!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
}
JOptionPane.showMessageDialog(null, "You have " + cash + " euros left...");
}
JOptionPane.showMessageDialog(null, "You have won games!");
System.exit(0);
}//Close Main
}//Close Class
If I understand it you should add the convertbet amount when you win and substract it when you loose to the cash.
if (num2 > num1) {
JOptionPane.showMessageDialog(null, "You Win!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
cash += convertbet
} else if (num2 < num1) {
JOptionPane.showMessageDialog(null, "You Lose!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
cash -= convertbet
} else {
JOptionPane.showMessageDialog(null, "No Winner!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
}
Watch out you where adding 10 to cash but assigning the returned value nowhere. You can use += operator to add and also assign the value to the variable.
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);
}
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;
Ok guys so I'm stuck trying to write some code in java, I cant get the code to display the pricing option for fullsize. I can't get the program to continue onto the second option I have listed as Case 2.
The project basically gives the user the option to ask if he is renting a car [Y or N]:
if Y is inputed the next question
it ask is "Compact of Full-size?",
if the user selects compact the project displays that the user has selected compact and
if the code displays fullsize the project displays that the user has selected fullsize.
Then it asks the user if they have a coupon if the users answer Y for the coupon the price is 7% off of 30.50.
If the user answers N the price is a normal 30.50. The fullsize normal price is 40.50 and the price with a coupon is 7% off of 40.50. The following is the code i have written currently.
The code:
public class CarRental {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50) - (30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50) - (40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye. ");
} else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
} else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
//case 2
response = input.next().toUpperCase();
if (response.equals("F")) {
System.out.println("You have selected Full-Size.");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
You're missing some }s after your else clauses. Example:
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//Put code that should only execute if you select Compact here.
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
//Put code that should only execute if you select Full-size here.
//Should have a } here!
//Put code that should always execute here.
Because you never close the block of code in the else clause, all of the code that follows is still part of the else, and therefore will only be executed if the else is selected, not under every circumstance as you had intended.
You are opening lots of brackets { but not closing them where you need }.
I usually not just handing the code, but I've noticed you done must of the job, but confused where to close the brackets and a little bit at the program flow.
I only changed it a bit, there is a lot that you can cut and reuse code.
public static void main(String[] args){
for(int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
}
else if(response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
The problem with this code is all your code is under the if statemente for Full-Size so the case 2 only executes when you select full-size , Yes to coupon and after showing the final message you press F again the code should look like this.
public class CarRental {
public static void main(String[] args){
for(int i=0; i<4; i++){
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
//case 2
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
As you can see in the code above is really important to correctly close conditional blocks so the code really does what you expect it to do.
Using flow diagrams is a good support for learning how programming languages really work.