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

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>"

Related

Format Flag Conversion Mismatch Exception

Write a program that inputs the name, quantity, and price of three items. The name may contain spaces. Output a bill with a tax rate of 6.25%. All prices should be output to two decimal places. The bill should be formatted in columns with 30 characters for the name, 10 characters for the quantity, 10 characters for the price, and 10 characters for the total. Sample input and output are shown as follows:
import java.util.Scanner;
public class ProjectLab {
public static final double SALES_TAX = 8.625;
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String item1, item2, item3;
int quantity1, quantity2, quantity3;
double price1, price2, price3;
//Input for the first Item
System.out.println("Input the name of item 1: ");
item1 = input.nextLine();
System.out.println("Input quantity of item 1: ");
quantity1 = input.nextInt();
System.out.println("Input price of item 1: ");
price1 = input.nextDouble();
String junk = input.nextLine(); //Junk Line
//Input for the second Item
System.out.println("Input name of item 2: ");
item2 = input.nextLine();
System.out.println("Input quantity of item 2: ");
quantity2 = input.nextInt();
System.out.println("Input price of item 2: ");
price2 = input.nextDouble();
String junk2 = input.nextLine(); //Junk line 2
//Input for the third item
System.out.println("Input name of item 3: ");
item3 = input.nextLine();
System.out.println("Input quantity of item 3: ");
quantity3 = input.nextInt();
System.out.println("Input price of item 3: ");
price3 = input.nextDouble();
double subtotal1 = price1 * quantity1;
double subtotal2 = price2 * quantity2;
double subtotal3 = price3 * quantity3;
System.out.println("Your bill: ");
System.out.println("Item Quantity Price Total");
System.out.println(item1 + " " + quantity1 + " " + price1 + " " + subtotal1 );
System.out.println(item2 + " " + quantity2 + " " + price2 + " " + subtotal2 );
System.out.println(item3 + " " + quantity3 + " " + price3 + " " + subtotal3 );
double finalSubtotal = (subtotal1 + subtotal2 + subtotal3);
System.out.printf("Subtotal %.2f \n" , finalSubtotal);
double tax = (finalSubtotal / SALES_TAX);
System.out.printf("8.265% Sales tax %.2f\n ", tax);
double total = tax + finalSubtotal;
System.out.printf("Total %.2f ", total);
}
}
Output:
Input the name of item 1:
Gummi Bears
Input quantity of item 1:
10
Input price of item 1:
1.29
Input name of item 2:
Monster Energy
Input quantity of item 2:
3
Input price of item 2:
2.97
Input name of item 3:
Ruffles Chips
Input quantity of item 3:
20
Input price of item 3:
1.49
Your bill:
Item Quantity Price Total
Gummi Bears 10 1.29 12.9
Monster Energy 3 2.97 8.91
Ruffles Chips 20 1.49 29.8
Subtotal 51.61
Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags =
at java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4298)
at java.util.Formatter$FormatSpecifier.checkBadFlags(Formatter.java:2997)
at java.util.Formatter$FormatSpecifier.checkGeneral(Formatter.java:2955)
at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2725)
at java.util.Formatter.parse(Formatter.java:2560)
at java.util.Formatter.format(Formatter.java:2501)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at ProjectLab.main(ProjectLab.java:65)
You need to escape your % with another %
System.out.printf("8.265%% Sales tax %.2f\n ", tax);
use String.format(..) at your last 3 outputs.
Try this
// also "\n" can be replaced with println
System.out.println(String.format("Subtotal %.2f " , finalSubtotal));
// also escape the first % sign
System.out.println(String.format("8.265 %% Sales tax %.2f ", tax));
More information for string fromatting here

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"

Print a multiline text document

I am having an issue with my code not printing out all of what is in a text document. My assignment is to take what is in a .txt file and put in a new .txt file I guess you could say "fancier."
This is the text file I am given.
Thomas Smith 3 2.25 44
Kim Johnson 2 55.60 35
John Doe 33 2.90 21
Karen Java 1 788.99 65
This is the "fancy" output I need(only It needs to output all of them).
The first name is: Thomas
The last name is: Smith
The total number of items bought is: 3
The customer's total is: 6.75
The customer's total rounded (cast) is: 6
The age of the customer is: 44
I think I have just been staring at it so long I'm just over looking it...
Scanner inFile = new Scanner(new FileReader("customer.txt"));
double options;
System.out.println("How would you like to input your data?\n1 Input information from customer.txt\n2 Input information from the keyboard.");
options = console.nextDouble();
if (options == 1){
//Variable to store first name
String firstName;
//Variable to store last name
String lastName;
//Variable to store how many items bought
int itemsBought;
//Variable to store the price per item
double itemPrice;
//Variable to store their age
int age;
while (inFile.hasNext()){
//Gets the first name
firstName = inFile.next();
//Gets the last name
lastName = inFile.next();
//Gets number of items bought
itemsBought = inFile.nextInt();
//Gets the price per item
itemPrice = inFile.nextDouble();
// Gets their age
age = inFile.nextInt();
PrintWriter outFile = new PrintWriter("programOutputFile.txt");
outFile.println("The customers first name is: " + firstName);
outFile.println("The customers last name is: " + lastName);
outFile.println("The customer bought " + (int)itemsBought + " items.");
outFile.println("The customers total is " + itemPrice);
outFile.println("The total cost rounded " + (int)itemPrice);
outFile.println("The customers age is: " + (int)age);
outFile.close();
}
}
else if (options == 2) {
String firstname;
String lastname;
int items = 0;
double price = 0;
int age1 = 0;
int counter; //loop control variable
counter = 0;
int limit; //store the number of items
System.out.print("Enter the number of entries you have "); //Line 1
limit = console.nextInt(); //Line 2
while (counter < limit) {
// It is asking for the user to input their first name
System.out.println("Please tell me what is your first name? ");
firstname = console.next();
// It is asking for the user to input their last name
System.out.println("What is your last name? ");
lastname = console.next();
// It is asking for the number of items they purchased
System.out.println("How many items did your purchase? ");
items = console.nextInt();
// Here it is asking for the total price they paid
System.out.println("What was the cost of each item? ");
price = console.nextDouble();
System.out.println("How old are you? ");
age1 = console.nextInt();
double total = items * price;
counter++;
if (counter != 0){
//Outputs the length of Firstname
System.out.println("The name is " + firstname.length() + " letters in your first name.");
//Outputs the first letter of LastName
System.out.println("The first letter of your last name is: " + lastname.charAt(0));
//Outputs the number of items bought
System.out.println("You bought " + items + " items.");
//Outputs Price
System.out.println("Your total price was " + total);
//Outputs the Price as a int number
System.out.println("Your total price rounded is " + (int)total);
//Outputs the age
System.out.println("They are " + age1 + " years old.");
PrintWriter outFile = new PrintWriter("programOutputFile.txt");
//Outputs the information given above into a .txt file
outFile.println("The customers first name is: " + firstname);
outFile.println("The customers last name is: " + lastname);
outFile.println("The customer bought " + (int)items + " items.");
outFile.println("The customers total is " + total);
outFile.println("The total cost rounded " + (int)total);
outFile.println("The customers age is: " + (int)age1);
outFile.close();
}
else
System.out.println("Invalid. Please try again.");
}
}
inFile.close();
}
As of right now it will print out Karen Java's line instead of Karen, John, Kim, and Thomas's. I have option 2 finished but again I am having the same problem of it only prints out the last input.
Any advise would be greatly appreciated!
You reopen the file in your loop each time you write. This has the effect of overwrite any previous contents of the file (the previous output you just wrote). declare outfile before the while loop and close it after.

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

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.

Categories