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()
Related
for (int i = 0; i < 2; i++) {
System.out.println("Please enter your name: ");
name = scan.nextLine();
peoples.setName(name);
System.out.println("Please enter your IC: ");
icNo = scan.nextLine();
peoples.setIcNo(icNo);
System.out.println("Please enter your marital status: ");
status = scan.nextLine();
taxes.setStatus(status);
System.out.println("Please enter your taxable income: ");
taxableIncome = scan.nextDouble();
taxes.setTaxableIncome(taxableIncome);
peoples.addPeople(name, icNo, taxableIncome, taxAmount);
}
System.out.printf("NAME " + "IC NO " + "TAXABLE INCOME " + "TAX AMOUNT");
System.out.println("");
System.out.println(peoples.toString());
This is a section of the code for the problem. I'm supposed to ask a person's name, ID, marital status and taxable income. I have three classes, one for the person's details, one to calculate the tax imposed and the main class here.
The information obtained from the people was supposed to be placed into an array but they're all in different data types. Well, name and ID are string types while both taxable income and tax amount are in double data types.
I tried to make an array in the people class but it didn't work out. I tried casting the array into string but it didn't work either. I'm supposed to obtain data from two or more people and print them out below a header. I just can't think of how it's supposed to store the data from user inputs and print them outside of the for loop. The user input should be stored as an array but I'm open to any other solutions.
You would need to have a Tax class that would store the tax info and it should contain a method that calculate tax like this
public class Tax {
private double taxableIncome_;
private double taxAmount_;
private String status_;
Tax(double taxableIncome, double taxAmount, String status) {
// initialize your members
}
public double calculateTax() {
//calculate tax
}
// implement setters and getters if needed.
}
Then you should create Person class that saves a person info and an instance of Tax like this:
public class Person {
private String name_;
private String id_;
private Tax tax_;
Person(String name, String id, Tax tax) {
// initialize members
}
#Override
public String toString() {
// return a string that has a person's information and tax's information
}
}
Then in your main program after creating an array of people you can use
Arrays.toString(pepoles) which will call toString for each object in your array
Example:
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Person[] people = new Person[2];
Scanner scan = new Scanner(System.in);
for(int i=0;i<2;i++)
{
String name = scan.nextLine();
System.out.println("Please enter your IC: ");
String icNo = scan.nextLine();
System.out.println("Please enter your marital status: ");
String status = scan.nextLine();
System.out.println("Please enter your taxable income: ");
double taxableIncome = scan.nextDouble();
System.out.println("Please enter your taxable Amount: ");
double taxAmount = scan.nextDouble();
people[i] = new Person(name, icNo, new Tax(taxableIncome, taxAmount,status));
}
System.out.println("NAME " + "IC NO " + "TAXABLE INCOME " + "TAX AMOUNT");
System.out.print(Arrays.toString(people));
}
}
This is the code with the main Class
I don't know how to update the stock. I tried encapsulation.
System.out.println("Cellphone Choice:\niPhone 10: $500\tSamsung: $450\tOppo: $300\n");
System.out.println("Input Name: ");
name = scan.nextLine();
System.out.println("Input Supplier: ");
supp = scan.nextLine();
try {
do {
System.out.println("Input Quantity: "+cp.getStock()+" STOCK"); //cp.getStock is initialized=80
quan = scan.nextInt();
}while(quan > cp.getStock());
System.out.println("Input Price of Selected Cellphone: ");
scan.nextLine();
price = scan.nextDouble();
} catch(InputMismatchException e) {
System.out.println("Please Input Number!");
}
cp = new Cellphone(name,supp,quan,price);
This code is from my other class
int stockCp = 80;
public void getProductionInfo() {
System.out.println("Buyer Name: "+name);
System.out.println("Supplier: "+supplier);
int qSold = stockCp - quantity;
System.out.println("Quantity left: "+qSold);
}
So the qSold is now the new Value of the total stock left.
example in the quantity is 10 so I got only 70 stocks left.
I did a do..while loop so that you can select cellphone choice again.
How to update the getStock to 70 since I took 10 quantity of stock before.
I think you just need to simply change the line
int qSold = stockCp - quantity;
to
stockCp = stockCp - quantity;
if I understand your problem correct.
im using for loops to ask user to input item to buy and calculate the price...then it will ask whether the user will continue add another item...so its a loop again...then when the user stop the purchase...then it will calculate the totalprice...so im using:
totalprice+=total;
but when the outer for loops will repeat for the second customer...the value of totalprice is still the value of purchase from first customer so it will add up...is there anyway i can revert totalprice value to 0 everytime it loop for the second customer?
this is my code for that method
public static void makeOrder() {
for (index = 0; index < date.length; index++) {
double price = 0;
int order;
char addOrder;
String resume;
System.out.print("\nCustomer" + (index + 1));
System.out.print("\nEnter your name: ");
String name = input.nextLine();
System.out.print("Enter the date of reservation(DD/MM/YY): ");
date[index] = input.nextLine();
System.out.print("Enter your type of table(Couple/Family): ");
String table = input.nextLine();
do {
System.out.println("BERKAT RESTAURANT MENU:\n\n MEALS \n1-Beef Bolognese: RM17.00\n2-Chicken Marsala: RM 13.00\n3-Spaghetti Carbonara: RM 9.00\n4-Fillet Mignon: RM12.00");
System.out.println("\nDRINKS \n5-Strawberry Fruit Punch: RM6.00 \n6-Vanilla Smoothies: RM 7.00\n7-Sky Juice: RM 3.00");
System.out.print("\nEnter your choice of meals/drink: ");
order = input.nextInt();
System.out.print("Enter the quantity: ");
int quantity = input.nextInt();
System.out.print("Do you want to add order?(Y/N): ");
addOrder = input.next().charAt(0);
double total = calculatePrice(order, quantity);
subtotal += total;
} while (addOrder != 'N');
System.out.println("");
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
System.out.printf("The total price you have to pay is: RM%6.2f ", subtotal);
System.out.println("");
System.out.println("Thank you for coming to our restaurant, Please come again!");
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
}
}// makeOrder method
i want to revert the subtotal value back to 0.00 everytime the 'for' loops back
You want to make sure that you initialize subtotal to 0 at the start of your outside for loop. This way for each customer, it is always 0, regardless of the number of items added to the order.
public static void makeOrder() {
double subtotal = 0;
for(index = 0, index < date.length; index++) {
subtotal = 0;
/* your other code here */
}
}
You should initialize subtotal to 0 at the start of your for loop.
public static void makeOrder()
{
for(index=0;index<date.length;index++)
{
double subtotal=0;
double price=0;
int order;
char addOrder;
String resume;
System.out.print("\nCustomer"+(index+1));
System.out.print("\nEnter your name: ");
String name=input.nextLine();
System.out.print("Enter the date of reservation(DD/MM/YY): ");
date[index]=input.nextLine();
System.out.print("Enter your type of table(Couple/Family): ");
String table=input.nextLine();
do{
System.out.println("BERKAT RESTAURANT MENU:\n\n MEALS \n1-Beef Bolognese: RM17.00\n2-Chicken Marsala: RM 13.00\n3-Spaghetti Carbonara: RM 9.00\n4-Fillet Mignon: RM12.00");
System.out.println("\nDRINKS \n5-Strawberry Fruit Punch: RM6.00 \n6-Vanilla Smoothies: RM 7.00\n7-Sky Juice: RM 3.00");
System.out.print("\nEnter your choice of meals/drink: ");
order=input.nextInt();
System.out.print("Enter the quantity: ");
int quantity=input.nextInt();
System.out.print("Do you want to add order?(Y/N): ");
addOrder=input.next().charAt(0);
double total=calculatePrice(order,quantity);
subtotal+=total;
}while(addOrder!='N');
System.out.println("");
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
System.out.printf("The total price you have to pay is: RM%6.2f ",subtotal);
System.out.println("");
System.out.println("Thank you for coming to our restaurant, Please come again!");
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
}
}//makeOrder method
thank you guys for your help...so i declare subtotal=0.00 and it work like a charm
public static void makeOrder()
{
for(index=0;index<date.length;index++)
{
double price=0;
double subtotal=0.00;
int order;
char addOrder;
String resume;
System.out.print("\nCustomer"+(index+1));
System.out.print("\nEnter your name: ");
String name=input.nextLine();
System.out.print("Enter the date of reservation(DD/MM/YY): ");
date[index]=input.nextLine();
System.out.print("Enter your type of table(Couple/Family): ");
String table=input.nextLine();
do{
System.out.println("BERKAT RESTAURANT MENU:\n\n MEALS \n1-Beef Bolognese: RM17.00\n2-Chicken Marsala: RM 13.00\n3-Spaghetti Carbonara: RM 9.00\n4-Fillet Mignon: RM12.00");
System.out.println("\nDRINKS \n5-Strawberry Fruit Punch: RM6.00 \n6-Vanilla Smoothies: RM 7.00\n7-Sky Juice: RM 3.00");
System.out.print("\nEnter your choice of meals/drink: ");
order=input.nextInt();
System.out.print("Enter the quantity: ");
int quantity=input.nextInt();
System.out.print("Do you want to add order?(Y/N): ");
addOrder=input.next().charAt(0);
double total=calculatePrice(order,quantity);
subtotal+=total;
}while(addOrder!='N');
System.out.println("");
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
System.out.printf("The total price you have to pay is: RM%6.2f ",subtotal);
System.out.println("");
System.out.println("Thank you for coming to our restaurant, Please come again!");
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
}
}//makeOrder method
I'm writing a program used to calculate the total sales of employees in a small business, and am trying to figure out how to restart the program based on a user input of y/n. I know that loops are what I need to use here, but need a push in the right direction.
Code:
import java.util.Scanner;
public class calcMain {
public static void main(String[]args){
double totalPay = 0, itemOne = 239.99, itemTwo = 129.75, itemThree = 99.95, itemFour = 350.89, commission;
int weeklyBonus = 200, numSold;
String employee1, employee2, employee3, employee4, yn;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the salesperson's name: ");
employee1 = kb.nextLine();
System.out.println("Please enter the number of Item 1 sold: ");
numSold = kb.nextInt();
totalPay += (itemOne * numSold);
System.out.println("Please enter the number of Item 2 sold: ");
numSold = kb.nextInt();
totalPay += (itemTwo * numSold);
System.out.println("Please enter the number of item 3 sold: ");
numSold = kb.nextInt();
totalPay += (itemThree * numSold);
System.out.println("Please enter the number of item 4 sold: ");
numSold = kb.nextInt();
totalPay += (itemFour * numSold);
System.out.println("The total weekly earnings for " +employee1+ " are: " +totalPay);
System.out.println("Would you like to input the sales of another employee? (y/n)");
yn = kb.next();
}
}
Put all the code inside a while loop that says while (yn.equalsIgnoreCase("y"))
Don't forget to initialize yn to y!
Second solution:
Modify the code so that it returns a string, and if the user inputs y, return y, or if the user inputs n, return n.
Put all that code inside a method (lets call it method x for now)
public static void main(String[] args) {
while(x().equalsIgnoreCase("y")){}
}
Using a do-while loop (while loop should have the same effect) and ask for (y/n) at the end.
Like this:
String yn;
do
{
// Your code here
// Ask for confirmation
}
while (yn.equals("y"));
Please help with my assignment. Here is the question:
Create a separate test driver class
called TestEmployeePayroll that will
test the EmployeePayroll class by
performing the following:
Prompt the user to enter the
employees’ ID number, First name, Last
name, Pay Category and Hours worked
(one at a time).
The user entry for employees ID
number must be exactly 5 digits long.
The user entry for Category must only
be accepted if it is in the range 1
to 4.
The user entry for Hours worked
must only be accepted if it is the
range 1 to 80.
This is what I did till now:
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
EmployeePayRoll obj1 = new EmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: "+ " ");
String EmployeeID = input.nextLine();
//How to check the range here if int is 5 digits long or not ?
System.out.println("Enter the first Name: "+ " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: "+ " ");
double PayCategory = input.nextDouble();
System.out.println("Enter the number of hours worked: "+ " ");
double HoursWorked = input.nextDouble();
}
}
You will probably want to use Integer.parseInt().
You can count the length of a String and then convert it to number, Oli Charlesworth told you how to convert it, or you can measure the number. It depends on what you want. Is 012345 a valid ID? It's a 6 char String but it is less than the biggest 5 digits number.
I think you almost got it...
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
// ... get the values, as you are doing already
// validate input
int employeeIdAsInteger = validateAndConvertEmployeeId(EmployeeId);
int payCategoryAsInteger = validateAndConvertPayCategory(PayCategory);
// ... and so on
}
private int validateAndConvertEmployeeId(String employeeId) {
// The user entry for employees ID number must be exactly 5 digits long.
if (employeeId == null || employeeId.trim().length() != 5) {
throw new IllegalArgumentException("employee id must be exactly 5 digits long");
}
// will throw an exception if not a number...
return Integer.parseInt(employeeId);
}
// ...
}
Depending on your objectives & constraints, you could look into the Pattern class and use a regular expression.
You can check for conditions like this.
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args) {
TestEmployeePayRoll obj1 = new TestEmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: " + " ");
String EmployeeID = input.nextLine();
if (EmployeeID.trim().length() != 5) {
System.out.println("--- Enter valid Employee ID number ---");
}
System.out.println("Enter the first Name: " + " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: " + " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: " + " ");
double PayCategory = input.nextDouble();
Double pay = new Double(PayCategory);
if (pay.isNaN()) {
System.out.println("***** Enter a valid Pay Category *****");
}
if (!(PayCategory >= 0 && PayCategory <= 5)) {
System.out.println(" --- PayCategory must be between 0 and 5");
}
System.out.println("Enter the number of hours worked: " + " ");
double HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if (hours.isNaN()) {
System.out.println("--- Enter a valid hours value ----");
} else {
if (!(HoursWorked >= 1 && HoursWorked <= 80)) {
System.out.println("--- Enter value between 1 and 80 ---");
}
}
}
}