/**
* #param newProfitMarginParam is used to set the gained profit margin.
*/
public void setCalculateProfitMargin(double newProfitMargin){
this.profitMargin = (this.sellingPrice - this.dealerCost) / this.sellingPrice;
}
/**
* A method to calculate the profit.
*/
public void calculateProfit(){
double dollar = this.sellingPrice - this.dealerCost;
}
public void main(String[] printDetails){
System.out.println("Jalopies Are Us Vehicle Summary:");
System.out.println("Vehicle: " + this.year + " " + this.make + " " + this.model);
System.out.println("Stock code: " + this.stockCode);
System.out.println("Dealer Cost: $" + this.dealerCost);
System.out.println("Selling Price: $" + this.sellingPrice);
System.out.println("Profit Margin: " + this.profitMargin + "%");
System.out.println("Dollare Profit: $");
calculateProfit();
}
e.g. here I want to add those aforesaid method in the main method.
How can I do that?
I add the last statement in the main method and I didn't get any Syntex error, but I'm not sure if it's correct or not.
Also how can I add the first method as well?
These concepts may help you understand better what is wrong with your code: Java Modifiers
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
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;
The project I am working on requires a bank account balance to be printed using a toString method. I am not allowed to add any methods to my current program, but I need to format my myBalance variable to a double that goes to two decimal places instead of one. In this particular instance my program should be printing 8.03, but it is printing 8.0.
Here is my toString method:
public String toString()
{
return"SavingsAccount[owner: " + myName +
", balance: " + myBalance +
", interest rate: " + myInterestRate +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
I am very new to Java still, so I would like to know if there is a way to implement %.2f into the string somewhere to format only the myBalance variable. Thank you!
Use String.format(...) for this:
#Override
public String toString() {
return "SavingsAccount[owner: " + myName +
", balance: " + String.format("%.2f", myBalance) +
", interest rate: " + String.format("%.2f", myInterestRate) +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
or more succinctly:
#Override
public String toString() {
String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" +
"number of withdrawals this month: %d, service charges for this month: %.2f, " +
"myStatusIsActive: %s]",
myName, myBalance, myInterestRate, myMonthlyWithdrawCount,
myMonthlyServiceCharges, myStatusIsActive);
return result;
}
Note that khelwood asked about my use of "%n" for a new-line token rather than the usual "\n" String. I use %n because this will allow the java.util.Formatter to get a platform specific new-line, useful in particular if I want to write the String to a file. Note that String.format(...) as well as System.out.printf(...) and similar methods use java.util.Formatter in the background so this applies to them as well.
Use String.format()
Example :
Double value = 8.030989;
System.out.println(String.format("%.2f", value));
Output :
8.03
I am a novice programmer who is learning Java and though my homework is complete I want to make it neater. I wanted to know if I can combine the following print methods into one and at least combine Kilograms to Pounds and Pounds to Kilograms Methods into one.
Note, I can't use anything more advanced then if statements and loops.
Because this is my first time posting and I want to make sure I provide all answerers with adequate information I have uploaded my Weight Conversion java file to here: Weight Conversion Java file.
Any other advice as to how to simplify the code, or following better code etiquette is welcomed too.
Here are the print statements:
/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS1( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print(dResult1 + " pounds is " + dResult2 + " kilograms.");
}// end method printRESULTS1
/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS2( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print( dResult1 + " kilograms is " + dResult2 + " pounds");
}// end method printRESULTS2
/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS3( double dResultOZ, double dResultLBS){
// Prints the result of Pounds to Kilograms
System.out.print( dResultOZ + " ounces is " + dResultLBS + " pounds");
}// end method printRESULTS3
/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS4( double dResultLBS, double dResultOZ){
// Prints the result of Pounds to Kilograms
System.out.print( dResultLBS + " pounds is " + dResultOZ + " ounces ");
}// end method printRESULTS4
For a start, consider this:
public static void printResults(
double dResultFrom,
String from,
double dResultTo,
String to)
{
System.out.print(dResultFrom + " " + from + " is " + dResultTo + " " + to);
}
Not sure about the whole context you're using it and about your limitations. Of course further refactoring steps are possible. For example:
public static void printResults(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
String formattedResult = formatResult(
resultFrom,
fromDescription,
resultTo,
toDescription);
System.out.print(formattedResult);
}
public static String formatResult(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
return formatQuantity(resultFrom, fromDescription)
+ " is "
+ formatQuantity(resultTo, toDescription);
}
public static String formatQuantity(double value, String description)
{
return value + " " + description;
}
Note much less code duplication than in your example, and a clear separation of responsibilities (formatting functions, and printing function). For example, if you had to print results to a file, not to the console, this design would prove more flexible.
Thanks for the help, it made me think harder as to how to simplify the code and organize it better. Also great advice on making sure that the code could be universal as in the print method could be used in another language that isn't English. What really helped was understanding that I can have more then 2 parameters in a Method.
public static void printRESULTS(int nConversion, double dResult1, double dResult2){
//Declare variable
String output = "";
//Pounds to Kilogram output
if (nConversion == 1){
output = dResult1 + " pounds is " + dResult2 + " kilograms.";
System.out.println(output);
}
//Kilograms to Pounds output
else if (nConversion == 2){
output = dResult1 + " kilograms is " + dResult2 + " pounds. ";
System.out.println(output);
}
//Ounces to Pounds output
else if (nConversion == 3){
output = dResult1 + " ounces is " + dResult2 + " pounds. ";
System.out.println(output);
}
//Pounds to Ounces output
else if (nConversion == 4){
output = dResult1 + " pounds is " + dResult2 + " ounces. ";
System.out.println(output);
}
I'm coding a simulation of a sports game, and it works fine for the most part; compiles and runs like it should. The directions ask that I I assume that I am supposed to be using printf and %.2f, but whenever I try to incorporate that into my code, it ceases to run properly. Help would be much appreciated!
import java.util.Scanner;
public class Team {
public String name;
public String location;
public double offense;
public double defense;
public Team winner;
public Team(String name, String location) {
this.name = name;
this.location = location;
this.offense = luck();
this.defense = luck();
}
public double luck() {
return Math.random();
}
Team play(Team visitor) {
Team winner;
double home;
double away;
home = (this.offense + this.defense + 0.2) * this.luck();
away = (visitor.offense + visitor.defense) * visitor.luck();
if (home > away)
winner = this;
else if (home < away)
winner = visitor;
else
winner = this;
return winner;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter name and location for home team (on separate lines)");
String homeName = s.next();
String homeLocation = s.next();
Team homeTeam = new Team(homeName, homeLocation);
System.out.println("Enter name and location for home team (on separate lines)");
String awayName = s.next();
String awayLocation = s.next();
Team awayTeam = new Team(awayName, awayLocation);
Team winnerTeam = homeTeam.play(awayTeam);
System.out.printf("Home team is:" + homeName + " from" + homeLocation + " rated" + homeTeam.offense + " (offense) +" + homeTeam.defense + " (defense)" + "\n");
System.out.printf("Away team is:" + awayName + " from" + awayLocation + " rated" + awayTeam.offense + " (offense) +" + awayTeam.defense + " (defense)" + "\n");
System.out.printf("Winner is:" + winnerTeam.name + " from" + winnerTeam.location + " rated" + winnerTeam.offense + " (offense) +" + winnerTeam.defense + " (defense)" + "\n");
}
You have misunderstood the printf method. You do not concatenate strings the way you do in this line and its successors (reformatted for width reasons):
System.out.printf("Home team is:" + homeName +
" from" + homeLocation +
" rated" + homeTeam.offense +
" (offense) +" + homeTeam.defense +
" (defense)" + "\n");
This is like the way an old coworker tried to use PreparedStatements to prevent SQL injection attacks, but constructed the query string by concatenation anyway, making the attempt ineffective. Instead, look at the signature of printf:
public PrintWriter format(String format, Object... args)
The first argument is a format string, which contains static text and format directives beginning with %. In typical use, each format directive corresponds to one argument of the method. Replace the interpolated variables with directives.
Strings are usually formatted with %s: s for string. Doubles are usually formatted with %f: f for float (or double). Characters between the % and the letter are options. So, let's replace the strings you interpolated with directives:
"Home team is: " + "%s" + // Inserted a space.
" from" + "%s" +
" rated" + "%6.2f" + // Six characters, 2 after the decimal.
" (offense) +" + "%6.2f" +
" (defense)" + "%n" // %n means the appropriate way to get a new line
// for the encoding.
Now we put it all together:
System.out.format("Home team is: %s from %s rated %6.2f (offense) + %6.2f (defense)%n",
homeName, homeLocation, homeTeam.offense, homeTeam.defense);
This is a lot simpler. Additionally, another reason to avoid interpolating strings in a format string is that the strings you interpolate may contain a percent sign itself. See what happens if you unguardedly write this:
String salesTax = "5%";
System.out.format("The sales tax is " + salesTax);
That's equivalent to
System.out.format("The sales tax is 5%");
Unfortunately, the percent sign is treated as a format directive, and the format statement throws an exception. Correct is either:
System.out.format("The sales tax is 5%%");
or
String salesTax = "5%";
System.out.format("The sales tax is %s", salesTax);
But now I should ask why you did not take homeName and homeLocation from Team. Certainly they are more relevant to Team than to each other. In fact, you should look up the Formattable interface, and with proper coding you can write:
System.out.format("%s%, homeTeam);
Try this:
public class A {
public static void main(String[] args) {
System.out.println(String.format("%.2f", 12.34123123));
}
}