How do I get user input from separate classes - java

My goal is to get an amount for an item and a description of that item. I want to get 10 inputs and their values. I don't know how to store their info without asking for one then the other. I want to be able to ask for the user to input the item then price and then store each of those values.
I was trying to create an array of objects to enter and then was suggested to use arraylists which I kind of understand but don't know how to implement in this case.
import java.util.ArrayList;
public class Invoice {
private ArrayList<Item> listOfItems;
public Invoice() {
listOfItems = new ArrayList<Item>();
}
public void addItem(Item item) {
listOfItems.add(item);
}
public double calculateNetItemCost() {
double netCost = 0;
for(Item currentItem : listOfItems) {
netCost += currentItem.getCost();
}
return netCost;
}
public double calculateTax(double taxRateAsADecimal) {
return calculateNetItemCost() * taxRateAsADecimal;
}
public double calculateGST() {
double GST = calculateNetItemCost() * 0.05;
return GST;
}
public double calculatePST() {
double PST = calculateNetItemCost() * 0.07;
return PST;
}
public double calculateTotalCost() {
double total = calculateGST() + calculatePST() + calculateNetItemCost();
return total;
}
}
public class Item {
private double amount;
private String description;
public Item(String description, double amount) {
this.amount = amount;
this.description = description;
}
public String toString() {
return description + ", $" + String.format("%.2f", amount);
}
public double getCost() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
import java.util.Scanner;
import java.util.ArrayList;
public class CustomerBuild {
public static void main(String[] args) {
ArrayList<String> description = new ArrayList<String>();
ArrayList<Double> amount = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
String userInput;
Item testItem = new Item("Apples", 4.00);
System.out.println(testItem);
Invoice testInvoice = new Invoice();
testInvoice.addItem(testItem);
double subTotal = testInvoice.calculateNetItemCost();
System.out.println(subTotal);
double GST = testInvoice.calculateGST();
System.out.println("GST: " + GST);
double PST = testInvoice.calculatePST();
System.out.println("PST: " + PST);
System.out.println("Total cost: " + testInvoice.calculateTotalCost());
}
}

This code snippet is what are you looking for. Asking the user for input then initializing the object using the values
Scanner input = new Scanner(System.in);
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
Item testItem = new Item(description, price);
For Looping:
for(int i =1;i<10;i++) {
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
testInvoice.addItem(new Item(description, price));
}

Related

How can I add a public method of priceAfterDiscount which returns the price after discount

How do I add the public method priceAfterDiscount which returns the price after discount in this class:
public class Book1 {
private String title;
private double price;
public static final double DISCOUNT=0.20;
public Book1(){
title="Unkown";
price=0.0;
}
public Book1(String name, double cost){
title=name;
price=cost;
}
public void setTitle(String n){
title=n;
}
public String getTitle(){
return title;
}
public void setPrice(double p){
price=p;
}
public double getPrice(){
return price;
}
}
public double priceAfterDiscount() {
if (price <= 0) {
return 0;
}
return price - (price * DISCOUNT);
}
public String toString() {
return title + " " + priceAfterDiscount();
}
Here is my main activity. Help me write the code.
import java.util.Scanner;
public class BookStore {
static Scanner console= new Scanner(System.in);
public static void main(String[]args){
Book1 b1,b2;
String title;
double price,newPrice;
System.out.print("Enter title: ");
title=console.next();
System.out.print("Enter price: ");
price=console.nextDouble();
/*
Create a book object based on the user input for b1
Call method priceAfterDiscount to get b1's new price
Print b1's information including title, price and newPrice*/
System.out.print("Enter another title: ");
title=console.next();
System.out.print("Enter another price: ");
price=console.nextDouble();
/*Create a book object based on the user input b2*/
if( ){ /*Compare the original prices of b1 and b2 have the same original price*/
System.out.println("Same price");
}
else{
System.out.println("Not Same Price");
}
Add $10 to b1's original price (hard code)
}
}
This should work:
public double priceAfterDiscount() {
if (price <= 0) {
return 0;
}
return price - (price * DISCOUNT);
}
public String toString() {
return title + " " + priceAfterDiscount();
}

Ending a Loop only after a user input gives a yes - Java

I am trying to create an app to take orders for a Hamburger and add additions. I want the additions to the burger to be based on a scanner input, but I am getting the error "Exception in thread "main" java.util.NoSuchElementException: No line found". Would appreciate if someone could help me understand where am I going wrong. I am a newbie to Java so please bear with me.
My code:
public class Hamburger {
private String name;
private double price;
private String breadRoll;
private String meat;
private String addition1Name;
private double addition1Price;
private String addition2Name;
private double addition2Price;
private String addition3Name;
private double addition3Price;
private String addition4Name;
private double addition4Price;
public Hamburger(double price, String meat) {
this.name = "Basic Hamburger";
this.price = price;
this.breadRoll = "White Bread";
this.meat = meat;
}
public void checkingAdditionCount(){
Scanner scanner = new Scanner(System.in);
System.out.println("Do you want to add more items?");
String answer = scanner.nextLine().toLowerCase();
boolean isCont = true;
while (isCont && scanner.hasNextLine()){
if (answer.equals("y")){
additions();
} else if (answer.equals("n")){
addAllItemsAndBill();
isCont = false;
scanner.close();
} else {
System.out.println("Please enter valid choice");
additions();
}
}
public void addAllItemsAndBill() {
System.out.println("Your total bill amount is " + this.price);
}
public void additions(){
Scanner scanner = new Scanner(System.in);
for (int count = 1; count < 5; count++){
System.out.println("Enter the addition name: ");
String additionName = scanner.nextLine();
System.out.println("Enter the addition price: ");
if (scanner.hasNextDouble()){
double additionPrice = scanner.nextDouble();
this.price += additionPrice;
}
scanner.nextLine();
checkingAdditionCount();
}
scanner.close();
this.addition1Name = name;
this.addition1Price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getBreadRoll() {
return breadRoll;
}
public void setBreadRoll(String breadRoll) {
this.breadRoll = breadRoll;
}
public String getMeat() {
return meat;
}
public void setMeat(String meat) {
this.meat = meat;
}
}
Try code, like:
while(true) {
if(scanner.nextLine().equals("y")) break;
}
It will be looping until user input not equal 'y' :)

Java: How would I declare an undefined number of object with user inputted data?

for my assignment I am suppose to have a user input the name and price of items. However, they are to enter in an unlimited amount of times until a sentinel value is used. I don't actually know how I'd go about doing this. The only way I know how to declare an object with user input is to use a scanner and then place that data within the arguments of a constructor. But that would only create a single object. Thanks!
import java.util.Scanner;
public class Item
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
}
private String name;
private double price;
public static final double TOLERANCE = 0.0000001;
public Item(String name,double price)
{
this.name = name;
this.price = price;
}
public Item()
{
this("",0.0);
}
public Item(Item other)
{
this.name = other.name;
this.price = other.price;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public void setName(String name)
{
this.name = name;
}
public void setPrice(double price)
{
this.price = price;
}
public void input(String n, double item)
{
}
public void show()
{
// Code to be written by student
}
public String toString()
{
return "Item: " + name + " Price: " + price;
}
public boolean equals(Object other)
{
if(other == null)
return false;
else if(getClass() != other.getClass())
return false;
else
{
Item otherItem = (Item)other;
return(name.equals(otherItem.name)
&& equivalent(price, otherItem.price));
}
}
private static boolean equivalent(double a, double b)
{
return ( Math.abs(a - b) <= TOLERANCE );
}
}
As I understood you want just initialize an array of obects.
Firstly you need initialize an array:
int n = scanner.nextInt(); // you may get n in other way
Item[] items = new items[n];
Then you can fill it with new instances of Item:
for(int i = 0; i < n; i++){
items[i] = new Item(); //constructor args may be here
}
To add undefined number of object best choice is List in java. By using your example i add some code in main() method as below :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Item> items = new ArrayList<>();
while (true) {
System.out.println("--------------------------------");
System.out.print("Enter item name :: ");
String name = input.next();
System.out.print("Enter item price :: ");
while (!input.hasNextDouble()) {
System.err.println("Invalid Price (Double) eg. 300");
System.out.print("Enter item price :: ");
input.next();
}
double price = input.nextDouble();
Item item = new Item(name, price); //creating object by passing value in constructor
items.add(item); //adding object in list
System.out.println("Do you want to add more items ? 'Y'=>Yes or 'N'=>No ");
String ans = input.next();
if ("N".equalsIgnoreCase(ans)) {
break;
}
}
//To retrive item object list
for (Item i : items) {
System.out.println(i);
}
}

Updating Object in ArrayList

I've written this code and everything seems to be correct but unfortunately its not giving the correct units sold. im trying to find out if the salesperson ID exists and update that record. Sometimes it prints the right information and sometimes it does not.
import java.util.*;
public class salesPerson {
//salesPerson fields
private int salespersonID;
private String salespersonName;
private String productType;
private int unitsSold = 0;
private double unitPrice;
//Constructor method
public salesPerson(int salespersonID, String salespersonName, String productType, int unitsSold, double unitPrice)
{
this.salespersonID = salespersonID;
this.salespersonName = salespersonName;
this.productType = productType;
this.unitsSold = unitsSold;
this.unitPrice = unitPrice;
}
//Accessor for salesPerson
public int getSalesPersonID(){
return salespersonID;
}
public String getSalesPersonName(){
return salespersonName;
}
public String getProductType(){
return productType;
}
public int getUnitsSold(){
return unitsSold;
}
public double getUnitPrice(){
return unitPrice;
}
public double getTotalSold(){
return unitsSold * unitPrice;
}
//Mutoators for salesPerson
public void setSalesPersonID(int salespersonID){
this.salespersonID = salespersonID;
}
public void setSalesPersonName(String salespersonName) {
this.salespersonName = salespersonName;
}
public void setProductType(String productType){
this.productType = productType;
}
public void setUnitsSold(int unitsSold){
this.unitsSold = this.unitsSold + unitsSold;
}
public void setUnitProce(double unitPrice){
this.unitPrice = unitPrice;
}
public static void main(String[] args)
{
ArrayList<salesPerson> salesPeople = new ArrayList<salesPerson>();
Scanner userInput = new Scanner(System.in);
boolean newRecord = true;
int salespersonID;
String salespersonName;
String productType;
int unitsSold = 0;
double unitPrice;
do{
System.out.println("Please enter the Salesperson Inoformation.");
System.out.print("Salesperson ID: ");
salespersonID = userInput.nextInt();
System.out.print("Salesperson Name: ");
salespersonName = userInput.next();
System.out.print("Product Type: ");
productType = userInput.next();
System.out.print("Units Sold: ");
unitsSold = userInput.nextInt();
System.out.print("Unit Price: ");
unitPrice = userInput.nextDouble();
if(salesPeople.size() == 0)
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}
else
{
for(int i=0; i < salesPeople.size(); i++) {
if(salesPeople.get(i).getSalesPersonID() == salespersonID)
{
salesPeople.get(i).setUnitsSold(unitsSold);
}
else
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}
//System.out.println(salesPeople.get(i).getSalesPersonName());
}
}
System.out.print("Would you like to enter more data?(y/n)");
String askNew = userInput.next();
newRecord = (askNew.toLowerCase().equals("y")) ? true : false;
}while(newRecord == true);
for(int i=0; i < salesPeople.size(); i++) {
System.out.println(salesPeople.get(i).getSalesPersonName() + ": "+salesPeople.get(i).getUnitsSold());
}
}
}
This method is probably wrong:
public void setUnitsSold(int unitsSold){
this.unitsSold = this.unitsSold + unitsSold;
}
Replace it by:
public void setUnitsSold(int unitsSold){
this.unitsSold = unitsSold;
}
You also have a problem on your main() method: The for creates a new SalesPerson instance for each element that has a different id from the one you've received on the input.
It's not related with your problem, but you should always (and I mean ALWAYS) start the name of Java classes with capital letters.

Java: ClassProblem. Java Novice

The problem I am dealing with is that I can't figure out how to make certain values in my class appear which they only return as zeros. I'm a beginner so I don't know much about Java but I have to make 4 classes or 3 types of employees and one class to output their values. But I can't get the values for the commission and union employ to show. Here is the code:
import java.util.Scanner;
// Base or Superclass
class Employee
{
String name;
String department;
double pay;
double hours;
double money;
double mission;
double rate;
double withheld;
double moneyc;
double moneyu;
double sales;
public void inputs()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter your name: ");
name = in.nextLine();
System.out.println("Enter your department: ");
department = in.nextLine();
System.out.println("Enter your pay per hour: ");
pay = in.nextDouble();
System.out.println("Enter how many hours you worked: ");
hours = in.nextDouble();
System.out.println("Enter your rate of commission(0.00): ");
rate = in.nextDouble();
System.out.println("Enter your withheld amount: ");
withheld = in.nextDouble();
System.out.println("Enter your sales amount: ");
sales = in.nextDouble();
money = pay * hours;
}
// Accessor Methods
public String getName()
{
return this.name;
}
public String getDepartment()
{
return this.department;
}
public Double getPay()
{
return this.pay;
}
public Double getHours()
{
return this.hours;
}
public Double getMoney()
{
return this.money;
}
public Double getMission()
{
return this.mission;
}
public Double getRate()
{
return this.rate;
}
public Double getWithheld()
{
return this.withheld;
}
public Double getMoneyc()
{
return this.moneyc;
}
public Double getMoneyu()
{
return this.moneyu;
}
public Double getSales()
{
return this.sales;
}
// Mutator Methods
public void setName(String n)
{
name = n;
}
public void setDepartment(String d)
{
department = d;
}
public void setPay(double p)
{
pay = p;
}
public void setHours(double h)
{
hours = h;
}
public void setMoney(double m)
{
money = m;
}
public void setMission(double mi)
{
mission = mi;
}
public void setRate(double r)
{
rate = r;
}
public void setWithheld(double w)
{
withheld = w;
}
public void setMoneyc(double mc)
{
moneyc = mc;
}
public void setMoneyu(double mu)
{
moneyu = mu;
}
public void setSales(double s)
{
sales = s;
}
}
class Last extends Employee
{
public void dinero()
{
Employee one = new Employee();
one.inputs();
// Union Employee
UnionEmployee three = new UnionEmployee();
three.Syndicate();
// Commission Employee
Commissioned two = new Commissioned();
two.sales();
System.out.println("\n"+ "Name: "+ one.getName());
System.out.println( "Department: "+ one.getDepartment());
System.out.println( "Hours: "+ one.getHours());
System.out.println( "Pay Rate: "+ one.getPay());
System.out.println("Your money is: "+ one.getMoney());
// Commissioned Employee
System.out.println( "\n"+ "Commissioned Employee");
System.out.println("Your money is: "+ one.getMoneyc());
System.out.println( "Your commission is: "+ one.getMission());
System.out.println("Your rate: "+ one.getRate());
// Union employee
System.out.println("\n"+"Union Employee");
System.out.println("Your money is: "+ one.getMoneyu());
System.out.println( "Your withheld is: "+ one.getWithheld());
}
}
// Derived or Subclass
class Commissioned extends Employee
{
public void sales()
{
moneyc = hours * pay;
// Commission
mission = sales * rate;
}
}
// Derived or Subclass
class UnionEmployee extends Employee
{
public void Syndicate()
{
if (hours <= 40) {
moneyu = (hours * pay) - withheld;
} else {
moneyu = (pay * hours * ((hours - 40) * 1.5)) - withheld;
}
}
}
public class WeiTry extends Last
{
public static void main(String[] args)
{
// Output
Last show = new Last();
show.dinero();
}
}
The only place I see your Employee's fields get set is inside a method called inputs()
one's values get populated because you call the inputs method on one but for your other employee types like your UnionEmployee three, inputs never called, and their fields never get set.
If you want your other employee's values to get set, it looks like you'll have to call their inputs method.
UnionEmployee three = new UnionEmployee();
three.inputs();
three.Syndicate();
or you can just copy them over
three.setName(one.getName());

Categories

Resources