Format Flag Conversion Mismatch Exception - java

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

Related

Code compiles but does not run completely. When the DoWhile loop is exited red error notes pop up

import java.util.Scanner;
public class TipCalculator{
static double Steak;
static double Ribs;
static double Salad;
static double Burger;
static double SoftDrink;
static double PintofBeer;
static double Wine;
static double Champagne;
static int i;
static double [] Choice = new double [15];
static double Subtotal;
static double Tax;
static double Tip;
static double Total;
public static void main (String args []){
Scanner scan = new Scanner (System.in);
Ribs = 25;
Steak = 35;
Salad = 5;
Burger = 15;
SoftDrink = 2;
PintofBeer = 5;
Wine = 6;
Champagne = 9;
Tax = 1.13;
do {
System.out.println("Please enter one of the following options, or enter 9 to go to your bill");
System.out.println("1. 12 oz Striploin Steak ");
System.out.println("2. 16 oz Baby Back Ribs ");
System.out.println("3. Ceaser Salad ");
System.out.println("4. House Burger ");
System.out.println("5. Soft Drink ");
System.out.println("6. Wine ");
System.out.println("7. Champagne ");
Choice [i] = scan.nextInt();
}
while (Choice [i] < 9);
if (Choice [i] == 9){
Subtotal = Choice[1] + Choice[2] + Choice[3] + Choice[4] + Choice[5] + Choice[6] + Choice[7] + Choice[8] + Choice[9] + Choice[10] + Choice[11] + Choice[12] + Choice[13] + Choice[14] + Choice[15];
System.out.println("Your subtotal is " + Subtotal);
}
System.out.println("Enter your tip percent");
Tip = scan.nextInt();
Total = ((Subtotal * Tax) * (Tip/10));
System.out.println("Your total is " + Total);
}
}
You are trying to access array index 15 (so the 16th element in array) which is technically not there as index start from 0. So the last index you can access is 14. Total elements are 15 as initialized by your code.
Change your line :
Subtotal = Choice[1] + Choice[2] + Choice[3] + Choice[4] + Choice[5] + Choice[6] + Choice[7] + Choice[8] + Choice[9] + Choice[10] + Choice[11] + Choice[12] + Choice[13] + Choice[14] + Choice[15];
To:
Subtotal = Choice[0] + Choice[1] + Choice[2] + Choice[3] + Choice[4] + Choice[5] + Choice[6] + Choice[7] + Choice[8] + Choice[9] + Choice[10] + Choice[11] + Choice[12] + Choice[13] + Choice[14];
This will get the flow rolling. (Although I will confess, the code is not doing what it is meant to be doing by just reading your code. But that is a different matter.)

Trying to understand why I can't round to 2 decimal places in one code but can in another thats virtually the same

I am writing a few java classes for a uni assignment and am having some trouble understanding what is going behind the scenes when I am trying to round to 2 decimal places. I have searched around but can't seem to find an answer that solves this particular version of the problem. So my code asks users to input prices into a cash register program and then prints the total price as well as the number of items. The total price has to be stored as an integer value (i.e 3.21 would be 321) but then outputted as a decimal value at the end. Here's my code:
public class CashRegister_Re_Implementation {
private double totalPrice;
private int itemCount;
CashRegister_Re_Implementation() {
totalPrice = 0;
itemCount = 0;
}
public double getTotal() {
String roundOff = String.format("%.2f", ((totalPrice * 100) / 10000));
double newDecimal;
newDecimal = Double.parseDouble(roundOff);
return newDecimal;
}
public int getItemCount() {
return itemCount;
}
public void addItem(double price) {
totalPrice += price * 100;
itemCount++;
}
}
class CashRegisterTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
CashRegister_Re_Implementation reg1 = new CashRegister_Re_Implementation();
int count1 = 0;
System.out.println("Register 1 (2 items)");
while (count1 < 2) {
System.out.print("Item price: £");
double price = scan.nextDouble();
reg1.addItem(price);
count1++;
}
CashRegister_Re_Implementation reg2 = new CashRegister_Re_Implementation();
int count2 = 0;
System.out.println("\nRegister 2 (2 items)");
while (count2 < 2) {
System.out.print("Item price: £");
double price = scan.nextDouble();
reg2.addItem(price);
count2++;
}
CashRegister_Re_Implementation reg3 = new CashRegister_Re_Implementation();
int count3 = 0;
System.out.println("\nRegister 2 (2 items)");
while (count3 < 2) {
System.out.print("Item price: £");
double price = scan.nextDouble();
reg3.addItem(price);
count3++;
}
System.out.println("\nFirst register. Total price: £" + reg1.getTotal() + "p for " + reg1.getItemCount() + " items");
System.out.println("Second register. Total price: £" + reg2.getTotal() + "p for " + reg2.getItemCount() + " items");
System.out.println("Third register. Total price: £" + reg3.getTotal() + "p for " + reg3.getItemCount() + " items");
}
}
It works fine except that if I enter all 1.00 I get this output:
Register 1 (2 items)
Item price: £1.00
Item price: £1.00
Register 2 (2 items)
Item price: £1.00
Item price: £1.00
Register 2 (2 items)
Item price: £1.00
Item price: £1.00
First register Total price: £2.0p for 2 items
Second register Total price: £2.0p for 2 items
Third register Total price: £2.0p for 2 items
Why am I getting £2.0 instead of £2.00?
I wrote this separately and it works absolutely fine:
public static void main(String[] args) {
double x = 100;
double y = 100;
double z = x + y;
String roundOff = String.format("%.2f", z);
System.out.println(roundOff);
}
Output:
200.00
Process finished with exit code 0
Why can't I get £2.00 in the exercise? Many thanks for any time taken to read all this :p
This is because your method getTotal has a return type of double but while concatenating the value in System.out.println you don't use formatting.
public double getTotal() {
String roundOff = String.format("%.2f", ((totalPrice * 100) / 10000));
double newDecimal;
newDecimal = Double.parseDouble(roundOff);
return newDecimal;
}
You should either return the formatted string from above method or change the print statements as follows:
System.out.println("\nFirst register. Total price: £" + String.format("%.2f", ((reg1.getTotal() * 100) / 10000)) + "p for " + reg1.getItemCount() + " items");
System.out.println("Second register. Total price: £" + String.format("%.2f", ((reg2.getTotal() * 100) / 10000)) + "p for " + reg2.getItemCount() + " items");
System.out.println("Third register. Total price: £" + String.format("%.2f", ((reg3.getTotal() * 100) / 10000)) + "p for " + reg3.getItemCount() + " items");
Note that a formatter has now been applied to the return value that you get from the method getTotal().
For a better reusability you should outline the first line in the method getTotal() in a new method like getTotalFormatted(). So you can use it in your rounding-algorithm and for printing too.

How do I output multiple different values of user input in Java?

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

Looping program back to ''menu''

I just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}

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.

Categories