What to do about dialog box being displayed outside of eclipse program - java

First I'm new to Java and am taking a beginner's course. Is the use of the % symbol in some cases not allowed in eclipse? in my code when I used the printf method if I use only one percent symbol it gives me an error however when I use 2 it works just fine. It runs the way it should but another issue I'm having is this code prints both to the console and in a dialog box and for some reason the dialog box doesn't get displayed in eclipse if i minimize eclipse i see it show up on my desktop. When i try it in Jgrasp this doesn't happen. Any ideas why this happens?
public class Project6
{
public static void main(String[] args)
{
double diamondCost; // Cost of diamond
double settingCost; // Cost of setting diamond
int numOrdered; // Number of diamonds ordered
double baseCost; // settingCost + diamondCost
double totalCost; // Total cost of diamond including labor and tax
double laborCost; // Cost of jewler's labor
double stateTax; // State tax
double luxuryTax; // Luxury tax
double finalAmountDue; // totalCost*numOrdered
double stateRate=0.10;
double luxuryRate=0.20;
double laborRate=0.05;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the cost of the diamond");
diamondCost = keyboard.nextDouble();
System.out.print("Enter the cost of setting the diamond");
settingCost = keyboard.nextDouble();
System.out.print("Enter the amount of diamonds you want to order");
numOrdered = keyboard.nextInt();
baseCost = diamondCost + settingCost;
luxuryTax = calcExtraCost(baseCost, luxuryRate);
stateTax = calcExtraCost(baseCost, stateRate);
laborCost = calcExtraCost(baseCost, laborRate);
totalCost = baseCost+luxuryTax+stateTax+laborCost;
finalAmountDue = calcExtraCost(totalCost, numOrdered);
System.out.println("Jasmine Jewelry:TOTAL COST BREAKDOWN");
System.out.printf("Diamond Cost: ----- $%.2f\n", diamondCost);
System.out.printf("Setting Cost: ----- $%.2f\n", settingCost);
System.out.printf("State Tax # 10%%: ----- $%.2f\n", stateTax);
System.out.printf("Luxury Tax # 20%%: ----- $%.2f\n", luxuryTax);
System.out.printf("Labor Cost # 5%%: ----- $%.2f\n", laborCost);
System.out.printf("Total Price each: ----- $%.2f\n", totalCost);
System.out.println("Number ordered: " + numOrdered);
System.out.printf("Final Amount Due: $%.2f", finalAmountDue);
DecimalFormat formatter = new DecimalFormat("0.00");
JOptionPane.showMessageDialog(null, "Jasmine Jewelry: TOTAL COST BREAKDOWN\n" + "Diamond Cost: ----- $" +
formatter.format(diamondCost) + "\n" +"Setting Cost: ----- $" + formatter.format(settingCost) + "\n" +
"State Tax # 10%: ----- $" + formatter.format(stateTax) + "\n" + "Luxury Tax # 20%: ----- $" +
formatter.format(luxuryTax) + "\n" + "Labor Cost # 5%: ----- $" + formatter.format(laborCost) + "\n" +
"Total cost each: ----- $" + formatter.format(totalCost) + "\n\n" +"Number ordered: " + numOrdered
+ "\n\nTotal Amount Due: $" + formatter.format(finalAmountDue));
keyboard.close(); // To close scanner object
System.exit(0);
} // End main method
static double calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
return extraCharge;
} // End method calcExtraCost
} // End class Project6

First of all printf uses % to mark positions which will be filled with variables later on
f.ex. your
System.out.printf("Diamond Cost: ----- $%.2f\n", diamondCost);
will insert the variable diamondCost at the position of the % character. If you want to print a % character you need to use %%.
Second the problem with your MessageDialog seems to be related that the MessageDialog has no parent.
Maybe how to show JOptionPane on the top of all windows is related to that.

Related

I have a multi-dimensional array of doubles (Double[][]) created in a child class and I need to print this array in parent class

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;

Displaying an output decimal with 2 places in java

I'm trying to find out why the %.2f declaration when outputting a decimal isn't working in my code, I've checked other similar questions but I can't seem to locate the issue in the specific logic error I'm receiving. When I go to compile my program it compiles fine, I go to run it and everything outputs fine until I get to the final cost where I'm trying to only display that decimal value with 2 decimal places.
I get an exception in thread "main"
Java.util.illegalformatconversionexception f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)
Here is my code:
import java.util.Scanner;
public class Cars
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int carYear, currentYear, carAge;
double costOfCar, salesTaxRate;
double totalCost;
String carModel;
System.out.println("Please enter your favorite car model.");
carModel = input.nextLine();
System.out.println("Please enter the year of the car");
carYear = input.nextInt();
System.out.println("Please enter the current year.");
currentYear = input.nextInt();
carAge = currentYear - carYear;
System.out.println("How much does the car cost?");
costOfCar = input.nextDouble();
System.out.println("What is the sales tax rate?");
salesTaxRate = input.nextDouble();
totalCost = (costOfCar + (costOfCar * salesTaxRate));
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars.");
}
}
I'm not exactly sure what's causing the issue.
Try:
System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);
Or the more readable:
System.out.printf("The model of your favorite car is %s," +
" the car is %d years old," +
" the total of the car is %.2f dollars.",
carModel, carAge, totalCost);
It's because %.2f is replaced with the entire second argument in that method call. The problem is that by specifying f in %.2f, you are saying that the second argument is a float or double. The second argument in this case is totalCost + " " + " dollars." which evaluates to a string.
To fix this problem, you need to make the second argument be a float or double. This can be achieved by moving + " " + " dollars." from the end of the second argument to the end of the first argument, like so:
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f" + " " + " dollars.",totalCost);
You can also remove many of the unnecessary concatenations from that line, resulting in this:
System.out.printf("The model of your favorite car is" + carModel + ", the car is " + carAge + " years old, the total of the car is %.2f dollars.", totalCost);
The variable has to go as a parameter to the System.out.printf() function. The "%.2f" will be replaced by the double value that is passed as the second parameter.
For Example:
System.out.printf("The value is %.2f", value);
The same thing is true for other variable types and for multiple variables,
String str = "The value is: ";
double value = .568;
System.out.printf("%s %.2f", str, value);
This will output: "The value is: .57"

I want to display the total purchase as 11.10 and not 11.1 [duplicate]

This question already has answers here:
Convert a number to 2 decimal places in Java
(4 answers)
Closed 8 years ago.
Enter the price of the book: $10
Book Cost: $10.00
State Tax Charged: $0.80
County Tax Charged: $0.30
Total Purchase Price: $11.10
Why I'm getting 11.1?
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System. in );
double bookCost = kbd.nextDouble();
double stateTax = bookCost * 0.08;
double countyTax = bookCost * 0.03;
double totalCost = bookCost + stateTax + countyTax;
System.out.print("Enter the price of the book: $");
System.out.println();
System.out.println("Book Cost: $" + bookCost);
System.out.println("State Tax Charged: $" + stateTax);
System.out.println("County Tax Charge: $" + countyTax);
System.out.println("Total Purchase Price: $" + totalCost);
}
}
System.out.println( String.format( "%.2f", totalCost ) );

How to show multiple messages within a single joptionpane message box?

I am new to these forums so I apologize in advance for any confusion/mistakes I might make.
I am trying to make a single message box with JOptionPane, and I want it to display many things such as:
JOptionPane.showMessageDialog( null, string1, int1, string2, int2);
Is there a way to use these message boxes to print multiple strings and ints within one box?
To clarify, basically I want the printlns at the bottom to be converted into one message box.
I am new to java.
import javax.swing.*;
public class PayrollJoption {
public static void main(String[] args) {
String nameFirst;
nameFirst = JOptionPane.showInputDialog("Enter Your First Name: ");
String nameLast;
nameLast = JOptionPane.showInputDialog("Enter Your Last Name: ");
int hourlyRate;
String hourlyRateString;
hourlyRateString = JOptionPane.showInputDialog("Enter Your Hourly Rate: ");
hourlyRate = Integer.parseInt(hourlyRateString);
int hoursWorked;
String hoursWorkedString;
hoursWorkedString = JOptionPane.showInputDialog("Enter Your Hours Worked: ");
hoursWorked = Integer.parseInt(hoursWorkedString);
double grosspay = hourlyRate * hoursWorked; // calculating gross pay
double taxWithholding = grosspay * 0.28; // calculating tax withholdings
double netPay = grosspay - taxWithholding; // calculating net pay
JOptionPane.showMessageDialog( null, "Name: ");
// This is the message box i was referring to
System.out.println("Name: " + nameFirst + " " + nameLast); // printing full name
System.out.println("Your Gross Pay Is: " + "$" + grosspay); // printing gross pay
System.out.println("Your Income Tax Is (28%) "); // showing tax percentage
System.out.println("Your Tax WithHolding is: " + "$" + taxWithholding); // showing tax withholdings
System.out.println("Your Net Pay Is: " + "$" + netPay); // printing net pay
System.out.println(" "); // skipping line for space
System.out.println("You Need A New Job!"); // printing text
}
}
You can try this :-
String to_print="Name: " + nameFirst+ " "+ nameLast +"\n"+
"Your Gross Pay Is: "+ "$" + grosspay+"\n"+
"Your Income Tax Is (28%) "+"\n"+
"Your Tax WithHolding is: "+ "$"+ taxWithholding+"\n"+
"Your Net Pay Is: "+ "$"+ netPay+"\n"+" \n"+
"You Need A New Job!"; //printing text
Remove all the bottom System.out.println() lines and then call,
JOptionPane.showMessageDialog( null,to_print);
I hope this works for you.If it doesn't,please comment below!
welcome to the forum, in the strings you can use \n to break message into lines:
"First line \n second line"
Also you can use HTML and the content of the string will be rendered:
"<html><b> a bold text </b></html>"

Compounding interest program in Java

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)));

Categories