Using scanner methods for simple Calculation in Java - java

I'm trying to create a simple program that asks the user to input three items, their quantities, and prices. The program must allow the item names to have spaces. Here is my code that I have written so far.
import java.util.Scanner;
public class AssignmentOne {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = kb.nextInt();
System.out.println("Please enter in the price of your item");
double price = kb.nextDouble();
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
System.out.println("\nPlease enter the quantity for this item");
int quantity2 = kb.nextInt();
System.out.print("\nPlease enter in the price of your item");
double price2 = kb.nextDouble();
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("\nPlease enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = kb.nextInt();
System.out.println("Please enter in the price of your item");
double price3 = kb.nextDouble();
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%30s", amount);
// System.out.printf("\n%s %25d %16.2f %11.2f", item, quantity, price, total);
// System.out.printf("\n%s %25d %16.2f %11.2f", item2,quantity2, price2, total2);
// System.out.printf("\n%s %25d %16.2f %11.2f", item3,quantity3, price3, total3);
System.out.printf("\n%30s", item);
System.out.printf("%30d", quantity);
System.out.printf("\n%30s", item2);
System.out.printf("\n%30s", item3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
}
My problem is that when I'm using String item = kb.nextLine(); here's an example of this process when entering the items
Please enter in your first item
soda
Please enter the quantity for this item
10
Please enter the price for this item
15
Please enter in your second item
Please enter the quantity for this item
At this point the first item is fine, but then it comes to the second item and it automatically inputs the second item line and moves straight onto the quantity, I don't understand how to fix this problem and I need to use nextLine(); so the item names can have spaces. Please help.

Try this code
import java.util.Scanner;
class AssignmentOne {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
System.out.println("\nPlease enter the quantity for this item");
int quantity2 = Integer.parseInt(kb.nextLine());
System.out.print("\nPlease enter in the price of your item");
double price2 =Double.parseDouble( kb.nextLine());
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("\nPlease enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price3 = Double.parseDouble(kb.nextLine());
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%30s", amount);
// System.out.printf("\n%s %25d %16.2f %11.2f", item, quantity, price, total);
// System.out.printf("\n%s %25d %16.2f %11.2f", item2,quantity2, price2, total2);
// System.out.printf("\n%s %25d %16.2f %11.2f", item3,quantity3, price3, total3);
System.out.printf("\n%30s", item);
System.out.printf("%30d", quantity);
System.out.printf("\n%30s", item2);
System.out.printf("\n%30s", item3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
}

Because you are using System.in, nothing is sent to the scanner until you've hit "enter". Meaning if you type "15" without hitting "enter", the kb.nextDouble(); call blocks. When you hit "enter" then kb.nextDouble(); reads "15", but there's still a newline in the scanner's buffer. That means this part of the code:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
Instantly reads the newline that was in the buffer from you typing "15" then hitting "enter". So it won't attempt to read an item name.
You can either replace all of your item name scanning from:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
to:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.next();
Or read the newline and parse the double when you scan for the price:
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());

kb.nextDouble();
I need to check, but it looks likely that nextDouble leaves the newline intact which then is inputed by the consequent `nextLine.

You can solve this problem in two different ways:
Replace .nextLine() with .next() in your code. (But doing this will not allow you to have spaces in the string.
When you read a primitive and then you read a text, add another .nextLine(); after it.
Using the second method in your case you'll have:
System.out.println("Please enter in the price of your item");
double price = kb.nextDouble();
String item2 = kb.nextLine(); // -------------> Added this line also here
//process for item two
System.out.println("\nPlease enter in your second item");
item2 = kb.nextLine();
Which will fix the first problem you have. Make the same for all other places, and your program will run as it supposed to.

Either Use different Scanner Objects for getting String and Numbers. This solves your problem.

Related

Parsing a string to boolean in java

I have the following simple sales program and am having trouble creating a restart loop around the program. My primary issue is converting the boolean from a string to a boolean type, I am getting an error in Eclipse that says, "The method parseBoolean(String) is undefined for the type Boolean".
However, I have defined a boolean variable at the top, boolean tryAgain = false;
and for some reason I cannot set the user input scanner to take the True or False value without an error. The error is occurring with the last line when I try to cast the nextLine from the user to boolean.
import java.util.Scanner;
public class Sales {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user input
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
while (tryAgain) {
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (True or False)");
tryAgain = Boolean.parseBoolean(userInput.nextLine());
}
}
}
The reason it gives you trouble is that when the user enters a double then hits enter, two things have just been entered - the double and a "newline" which is \n.
The method you are calling, "nextDouble()", only reads in the double, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you have to call nextLine() before your code would work.
Add this line before last line .
userInput.nextLine();
Well, I couldn't get it to work with a boolean for some reason, so I changed to a do while loop. Here is the final code. Also I did use the tip for clearing out the nextLine().
import java.util.Scanner;
public class Sales2 {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user inputjea
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
String answer; //Define var type of String for do while loop to restart program
do { //Do this loop while string == (last line of code while loop)
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (yes or no)"); //Prompt user for restart
userInput.nextLine(); //Clear scanner
answer = userInput.nextLine();
}
while (answer.equalsIgnoreCase("Yes")); //Connected to do while loop
//
}
}
Scanner supports nextBoolean(). Just use it:
tryAgain = userInput.nextBoolean()

How can I make a user input 20 be read by the program as 20% or 0.20

This is the part where I ask the user to input the following.
Enter the item name: Shirt
Original price of the item: 700
Marked-up Percentage: 20
Sales Tax Rate: 7
Output:
Item to be sold : Shirt
Original price of the item: 700.00
Price after mark-up: 840.00
Sales tax: 58.80
Final price of item: 898.80
so my question is how can I make that 20 and 7 input be read by the program as percentages.
import java.util.*;
import javax.swing.*;
public class lab3 {
public static void main(String[] args) {
JOptionPane jo=new JOptionPane();
String item=jo.showInputDialog("Item to be sold: ");
double Oprice=Double.parseDouble(
jo.showInputDialog("Original price of the item: "));
double mup=Double.parseDouble(
jo.showInputDialog("Marked-up percentage: "));
double str=Double.parseDouble(
jo.showInputDialog("Sales Tax Rate: "));
double pamu=(Oprice*mup)+Oprice;
double ST=pamu*str;
double result=pamu+ST;
String hold= "\n| Item to be sold \t: "+item+"\t |"
+"\n| Original price of the item \t: "+Oprice+"\t |"
+"\n| Price after mark-up \t: "+pamu+"\t |"
+"\n| Sales Tax \t: "+ST+"\t |"
+"\n| Final price of the item \t: "+result+"\t |";
jo.showMessageDialog(null, new JTextArea(hold));
}
}
That is my actual code. sorry if its messy. like I said still new to this
Let's use Scanner for reading from user:
Scanner sc = new Scanner(System.in);
double percentage = 0.01 * sc.nextInt();
will do the trick.
double pamu = (Oprice*(mup/100)) + Oprice; // enter code here
double ST = pamu*(str/100) ;
double result = pamu+ST ;
I think this should work.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name:");
String item;
keyboard.nextLine();
System.out.println("Original Price of item:");
double originalPrice;
keyboard.nextDouble();
System.out.println("Marked up percentage:");
double markedUpPercentage;
keyboard.nextDouble();
markedUpPercentage = markedUpPercentage/100; //this is what you want
System.out.println("Sales tax rate:");
double salesTaxRate;
keyboard.nextDouble();
salesTaxRate = salesTaxRate/100; //same thing here
//now output
System.out.println("Item to be sold: " + item);
System.out.println("Original price of the item: " + originalPrice);
System.out.println("Price after mark up: " + (originalPrice + originalPrice * markedUpPrice));
//similarly, do for sales tax

Couple of errors

When I call this code in Terminal on my Mac it tells me "could not find or load main class" also it gives me a lot of errors on all of my code regarding printf.
I am new to Java so I assume this code is error ridden.
All I am really asking is how to fix it so it will run in terminal when I type "java itemprice" for it to not show an error.
Also I would like some help with the system.out.printf code.
import java.util.Scanner;
public class itempricecalc {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("What is your first name?");
String fname = scanner.nextLine();
String invf = fname.substring(0,2);
System.out.print("What is your last name?");
String lname = scanner.nextLine();
String invl = lname.substring(0,2);
System.out.println("Your name is: " +fname + lname);
System.out.println("What is your zipcode?");
int zipcode = scanner.nextInt();
invoice = (invf + invl + zipcode);
double salestax = 6.25;
double subtotal = 0;
System.out.println("What is item 1 called?")
String itemonename = scanner.nextLine():
System.out.println("Enter price of item 1");
double itemone = scanner.nextDouble();
System.out.println("How many of item 1 did you purchase?");
int itemoneamount = scanner.nextInt();
System.out.println("What is item 2 called?")
String itemtwoname = scanner.nextLine():
System.out.println("Enter price of item 2");
double itemtwo = scanner.nextDouble();
System.out.println("How many of item 2 did you purchase?");
int itemtwoamount = scanner.nextInt();
System.out.println("What is item 3 called?")
String itemthreename = scanner.nextLine():
System.out.println("Enter price of item 3");
double itemthree = scanner.nextDouble();
System.out.println("How many of item 3 did you purchase?");
int itemthreeamount = scanner.nextInt();
double itemonetp = itemoneamount * itemone;
double itemtwotp = itemtwoamount * itemtwo;
double totalprice = itemonetp + itemtwotp;
subtotal = subtotal + totalprice;
double taxtotal = subtotal * salestax;
System.out.print("Your name is: " + fname + " " + lname)
System.out.printf(“Invoice: %.2f”, invoice);
System.out.printf(“Total price of item one is + %.2f”, itemonetp);
System.out.printf(“Total price of item two is + %.2f”, itemtwotp);
System.out.printf(“Total price of your purchase is + %.2f”, totalprice);
System.out.printf(“Your total with tax comes to + %.2f”, taxtotal);
System.out.printf(“You purchased + %.2f + amount of item one”, itemoneamount);
System.out.printf(“You purchased + %.2f + amount of item two”, itemtwoamount);
}
}

Formatting perfectly with printf in Java

I'm trying to make my program print out a bill of three items with their names quantities and prices. Everything works fine, all I need is how to formate the prices and totals in order to make all the decimals line up everytime, no matter how big the number. Here's my code
import java.util.Scanner;
class AssignmentOneTest {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());
//process for item two
System.out.println("Please enter in your second item");
String item2 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity2 = Integer.parseInt(kb.nextLine());
System.out.print("Please enter in the price of your item");
double price2 =Double.parseDouble(kb.nextLine());
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("Please enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price3 = Double.parseDouble(kb.nextLine());
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%28s %11s %11s", "Quantity", "Price", "Total");
//complete item one format
System.out.printf("\n%-30s", item);
System.out.printf("%-10d", (int)quantity);
System.out.printf("%-10.2f", (float)price);
System.out.printf(" " + "%-10.2f", (float)total);
//complete item two format
System.out.printf("\n%-30s", item2);
System.out.printf("%-10d", (int)quantity2);
System.out.printf("%-10.2f", (float)price2);
System.out.printf(" " + "%-10.2f", (float)total2);
//complete item three format
System.out.printf("\n%-30s", item3);
System.out.printf("%-10d", (int)quantity3);
System.out.printf("%-10.2f", (float)price3);
System.out.printf(" " + "%-10.2f", (float)total3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
The problem is that every time the prices are the same, everything lines up, but lets say I type in a price of 50.00 and a price of 2.50 for two different items, then the items price and total decimal points don't all line up, please help.
I find that lining up titles and columns is a lot easier if I do the output in a matched pair of functions, one for the titles and one for the data, e.g.:
public static void prLine (String item, int quantity, double price, double total) {
System.out.printf("\n%-20.20s %10d %10.2f %10.2f", item, quantity,
price, total);
}
public static void prTitles () {
System.out.printf("\n%-20s %10s %10s %10s", "Item", "Quantity",
"Price", "Total");
}
You can see that it is easy to get the field widths to correspond nicely this way. Then I can use these functions as follows:
prTitles ();
prLine (item,quantity,price,total);
prLine (item2,quantity2,price2,total2);
prLine (item3,quantity3,price3,total3);
... and I get lined-up output in the style I think you're looking for:
Your bill:
Item Quantity Price Total
first 1 1.50 1.50
second 10 12.50 125.00
third 456 322.00 146832.00
Putting the output code in functions also greatly reduces the number of lines of code in the main() function.
You will have to control this yourself.
Basically I'm thinking there's 2 different ways to handle this.
The first way is to check the length of the output before you output it by converting whatever is necessary into a string, then checking it's length. After you do that you can add in spaces in between the prices to make them line up. Something like this may be able to achieve that, of course integrated however you need it:
int length = String.valueOf(1000d).length();
The second way I'm thinking of is adding tabs between the prices to have it auto line up itself. Of course this way you'll have extra spaces most the time between all of the outputs and you'll have to make sure the item name isn't long enough that you'll need 2 tabs, or more.
Good luck! If you need more clarification, please let me know.
EDIT: To make it a bit better, you can incorporate the length checking above and use printf's width specifier to pad in the spaces. It is a bit better.
// calculate padding based on the length of the output
String format = "%" + padding + "d";
System.out.printf(format, variables);
EDIT2: OOP version of this, it isn't perfect but does it very well :)
EDIT3: Added some comments into the code.
http://pastebin.com/CqvAiQSg

System.out.print-method doesn´t work right

I am doing excercises in a book called "Java, how to program". I have created a small program with 2 classes. The program is supposed to be used by a hardware store to represent an invoice for items sold. It is supposed to includ 4 pieces of information: A string value for the items number, a string value which describes the product, an int value for the quantity of items sold, and a double value for the items price. I have created 2 objects of the class in a class which contains the main method. I am supposed to use "set and get-methods" for each instance variables.
The problem is that when the programs prompts the user to write the values of the variables, it doesn´t read the first value for the variable "second items number" (Line 5 in the copy of the command window under). I really can´t read in the code why this happens. Can anyone please help me?
The code of the two classes are as follows:
public class aInvoice
{
private String number;
private String description;
private int quantity;
private double price;
public aInvoice(String pNumber, String pDescription, int pQuantity, double pPrice)
{
number = pNumber;
description = pDescription;
if (pQuantity < 0)
{quantity = 0;}
else
{quantity = pQuantity;}
if (pPrice < 0)
{price = 0;}
else
{price = pPrice;}
}
public String getNumber()
{
return number;
}
public String getDescription()
{
return description;
}
public int getQuantity()
{
return quantity;
}
public double getPrice()
{
return price;
}
double totalAmount;
public double getaInvoiceTotalAmount()
{
return quantity * price;
}
}
and:
import java.util.Scanner;
public class aInvoiceTest
{
public static void main(String[]args)
{
String partNumber1 = null;
String partDescription1 = null;
int partQuantity1 = 0;
double partPrice1 = 0.0;
String partNumber2 = null;
String partDescription2 = null;
int partQuantity2 = 0;
double partPrice2 = 0.0;
Scanner input = new Scanner (System.in);
System.out.print( "Enter first items number: ");
partNumber1 = input.nextLine();
System.out.print( "Enter description: ");
partDescription1 = input.nextLine();
System.out.print( "Enter quantity: ");
partQuantity1 = input.nextInt();
System.out.print( "Enter price: $");
partPrice1 = input.nextDouble();
System.out.print( "Enter second items number: ");
partNumber2 = input.nextLine();
System.out.print( "Enter description: ");
partDescription2 = input.nextLine();
System.out.print( "Enter quantity: ");
partQuantity2 = input.nextInt();
System.out.print( "Enter price: $");
partPrice2 = input.nextDouble();
aInvoice aInvoice1 = new aInvoice(partNumber1, partDescription1, partQuantity1, partPrice1);
aInvoice aInvoice2 = new aInvoice(partNumber2, partDescription2, partQuantity2, partPrice2);
System.out.printf( "\n\nPart 1´s item number: %s\nItem description: %s\nQuantity: %d\nPrice each: $ %.2f\n\n", aInvoice1.getNumber(), aInvoice1.getDescription(), aInvoice1.getQuantity(), aInvoice1.getPrice () );
System.out.printf( "\n\nPart 2´s item number: %s\nItem description: %s\nQuantity: %d\nPrice each: $ %.2f\n\n", aInvoice2.getNumber(), aInvoice2.getDescription(), aInvoice2.getQuantity(), aInvoice2.getPrice () );
System.out.printf( "Total amount: $ %.2f\n\n", (aInvoice1.getaInvoiceTotalAmount() + aInvoice2.getaInvoiceTotalAmount()));
}
}
THe reading in the command window is:
Enter first items number: 44
Enter description: pc
Enter quantity: 1
Enter price: $10
Enter second items number: Enter description: phone
Enter quantity: 1
Enter price: $100
Part 1´s item number: 44
Item description: pc
Quantity: 1
Price each: $ 10.00
Part 2´s item number:
Item description: phone
Quantity: 1
Price each: $ 100.00
Total amount: $ 110.00
This is because after you read input using input.nextInt() or input.nextDouble() you need to clear the buffer before trying to read in another string.
When the user types in 5.0 the 5.0 is taken from the input buffer but the carriage return is left. You can put a input.nextLine() and this will clear that carriage return for you.
so your code should look like
System.out.print( "Enter price: $");
partPrice1 = input.nextDouble();
input.nextLine();
System.out.print( "Enter second items number: ");
partNumber2 = input.nextLine();
System.out.print( "Enter description: ");
partDescription2 = input.nextLine();
System.out.print( "Enter quantity: ");
partQuantity2 = input.nextInt();
System.out.print( "Enter price: $");
partPrice2 = input.nextDouble();
Basically, the problem is that when you call nextInt/nextDouble, those functions only grab the number part of what is actually present in your input stream. They don't read the enter character that hitting the "enter" key put there. Just put a input.nextLine(); after every input.nextInt(), etc.
This appears to be the problem you are seeing: Using scanner.nextLine()

Categories

Resources