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.
Related
I have to write a Java program with do while loop. Basically it's like self-checkout register in grocery stores. At first program prompts user to enter Item 1 name and price, after we enter it asks "do you want to add more?" and prompts user. if we say yes then it repeats, add Item 2 (item number increments) name and price. So it goes like this till we say "no" or till entering 10 items. And after that program prints all item numbers correspondingly their names, and prices one by one. Also calculates total of all items. My code prints only last item number, name, price and total. I don't know how to merge array to do while.
Example how it should look:
_output: Enter Item1 and its price:_
_input: Tomatoes_
_input: 5.5_
_output: Add one more item?_
_input: yes_
_output: Enter Item2 and its price:_
_input: Cheese_
_input: 3.5_
_output: Add one more item?_
_input: yes_
_output: Enter Item3 and its price:_
_input: Apples_
_input: 6.3_
_output: Add one more item?_
_input: no_
_output: Item1: Tomatoes Price: 5.5, Item2: Cheese Price: 3.5, Item3: Apples Price: 6.3_
_output: Total price: 15.3_
Here's my code. It prints only last item's number, name and price with total. But can't manage to print all of them one by one as in example.
Scanner scan = new Scanner(System.in);
String item;
double price;
int i=1;
double total=0;
String quest;
String items [] = {};
do {
System.out.println("Enter item " + i + " and it's price:");
item = scan.next();
price=scan.nextDouble();
i++;
total=total+price;
System.out.println("Add one more item?");
quest=scan.next();
} while (quest.equalsIgnoreCase("yes")) ; {
System.out.println("Item "+i+": " + item + " Price: " + price + ",");
System.out.println("Total price: " + total);
}
You need to store each input in an array or collection, such as ArrayList.
If you choose to use an array, you can ask the user how many items will be entered then use that value for the length of the array:
System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();
String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];
If you decide you use a list, you do not need to ask the user for the list size, since lists are dynamically expanding data types:
List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();
Then for every iteration of your loop, you save the values into the arrays/lists:
System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();
String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];
for(int i = 0; i < ararySize; i++) {
System.out.println("Enter item " + (i + 1) + " and it's price:");
itemNames[i] = scan.next();
itemPrices[i] = scan.nextDouble();
// ...
}
// ...
Or for the list approach:
List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();
do {
System.out.println("Enter item " + i + " and it's price:");
itemNames.add(scan.next());
itemPrices.add(scan.nextDouble());
// ...
} while (quest.equalsIgnoreCase("yes")); {
// ...
}
Then you can iterate over the list/array to print your output:
for(int i = 0; i < itemNames.length; i++) {
String name = itemNames[i];
double price = itemPrices[i];
System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}
For list:
for(int i = 0; i < itemNames.size(); i++) {
String name = itemNames.get(i);
double price = itemPrices.get(i);
System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}
I finally solved the task. Thanks everybody who helped, really appreciated. Here's the code:
Scanner scan = new Scanner(System.in);
String itemName;
double price;
String[] items = new String[10];
double[] prices = new double[10];
int itemNumbers[] = new int[10];
String answer;
double total = 0;
int i = 1;
int index = 0;
do {
System.out.println("Enter item " + i + " and it's price:");
itemName = scan.next();
price = scan.nextDouble();
scan.nextLine();
total = total + price;
items[index] = itemName;
prices[index] = price;
itemNumbers[index] = i;
index++;
System.out.println("Add one more item?");
answer = scan.next();
i++;
} while (answer.equalsIgnoreCase("yes") && i <= 10); {
for (int j = 0; j < index; j++) {
System.out.print("Item " + itemNumbers[j] + ": " + items[j] + " price: " + prices[j] + ",");
}
}
System.out.println("\nTotal price: " + total);
This version works too. Without arrays.
String shoppingList = "";
String item = "";
String addMore = "";
double price = 0;
int count = 1;
double totalPrice = 0;
do {
System.out.println("Enter Item"+ count + " and its price:");
item = scan.next();
price = scan.nextDouble();
shoppingList += ("Item" + count + ": " + item + " Price: " + price + ", ");
totalPrice += price;
System.out.println("Add one more item?");
addMore = scan.next();
count++;
} while (addMore.equalsIgnoreCase("yes"));
System.out.println(shoppingList.substring(0, shoppingList.length()-2));
System.out.println("Total price: " + totalPrice);
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 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);
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I can't seem to figure out why the string college doesn't show when I run this. There are no errors when I compile it. What am I doing wrong? Everything else is working. It's probably an easy fix, but I'm new and just starting to learn Java.
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String college;
String profession;
String animal;
String petname;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}
Call keyboard.nextLine() after age = keyboard.nextInt();.
Currently int value is read as age and college = keyboard.nextLine(); reads the remainder of the line which container your int, which is empty. So the correct form should be:
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
Other possible solution to avoid the extra call to nextLine() is reading the whole line as a String and then parsing that String to an integer, for example:
age = Integer.parseInt(keyboard.nextLine());
Put keyboard.nextLine() after this line:
int age=keyboard.nextInt();
This is a common problem that usually happens when you use nextLine() method after nextInt() method of Scanner class.
What actually happens is that when the user enters an integer at int age = keyboard.nextInt();, the scanner will take the digits only and leave the new-line character \n. So you need to do a trick by calling keyboard.nextLine(); just to discard that new-line character and then you can call String college = keyboard.nextLine(); without any problem.
this is taken from Reading Strings next() and nextLine() Java
The problem with your code is using nextLine() after nextInt() & you have an additional nextLine()
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine(); --> this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
What you should do is :
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine(); -->add this line
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// keyboard.nextLine(); --> remove this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
A better way of doing it would be : (read about Integer.pasrseInt(String))
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String profession;
String animal;
String petname;
String college;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println(college);
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}
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>"