I'm having trouble doing a user-defined method in my program here, would it be nice if anyone can help me
package Ex_9_2;
public class TestStock {
public static String price;
//main
public static void main(String[] args) {
Stock stock = new Stock("ORCL", "Oracle Corporation");
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);
System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);
System.out.println(stock);
// Display stock info
System.out.println("Previous Closing Price: " + stock.getPreviousClosingPrice());
System.out.println("Current Price: " + stock.getCurrentPrice());
System.out.println("Price Change: " + stock.changePercent());
}
}
Here's my other class
package Ex_9_2;
public class Stock {
private String symbol;
private String name;
private double previousClosingPrice;
private double currentPrice;
public Stock() {
}
public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}
public String getSymbol() {
return this.symbol;
}
public String getName() {
return this.name;
}
public double getPreviousClosingPrice() {
return previousClosingPrice;
}
public double getCurrentPrice() {
return currentPrice;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public void setName(String name) {
this.name = name;
}
public void setPreviousClosingPrice(double price) {
this.previousClosingPrice = price;
}
public void setCurrentPrice(double price) {
this.currentPrice = price;
}
public double changePercent() {
return (currentPrice - previousClosingPrice) / previousClosingPrice;
}
#Override
public java.lang.String toString(){
return "\nYour Company's name is " + this.name
+ "\nYour Company's Symbol is " + this.symbol;
}
I can't seem to make a user-input in my main for this problem:
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);
and this:
System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);
please help,
You can use java.util.Scanner class to take inputs from the user.
Declare a Scanner variable in your main function:
Scanner scan = new Scanner(System.in);
Then use scan.nexDouble() for taking input from the user. For example:
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(scan.nextDouble());
Related
I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
public String getStreetName() {
return streetName;
}
public void setStreetName (String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity (String city) {
this.city = city;
}
public int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class
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();
}
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' :)
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));
}
I'm made a program that creates an invoice but when it comes numbers in the thousands the output isn't neat and ruins everything. How do I fix this so the program's columns are more aligned with numbers like this? Here is the code I used to create the program. If anyone could help, it would be much appericated.
Here's the one with the main method...
public class InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress=new Address("Sam's Small Appliances", "100 Main
Street", "Anytown", "CA", "98765");
Invoice samsInvoice =new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95),3);
samsInvoice.add(new Product("Hair Dryer", 24.95),1);
samsInvoice.add(new Product("Car Vacuum",19.99),2);
samsInvoice.add(new Product("Nano Parts",100000),1);
samsInvoice.addSimple(new Product("Shipping",5.00));
System.out.println(samsInvoice.format());
}
}
These are the other programs needed for the program to work
import java.util.ArrayList;
public class Invoice
{
public Invoice(Address anAddress)
{
items=new ArrayList<LineItem>();
billingAddress=anAddress;
simpleItems= new ArrayList<SimpleLineItem>();
}
public void addSimple(Product aProduct)
{
SimpleLineItem anItem= new SimpleLineItem(aProduct);
simpleItems.add(anItem);
}
public void add(Product aProduct, int quantity)
{
LineItem anItem=new LineItem(aProduct,quantity);
items.add(anItem);
}
public String format()
{
String r=" I N V O I C E\n\n"+billingAddress.format()+String.format("\n\n%-30s%8s%5s%8s\n","Description", "Price","Qty","Total");
for(LineItem i:items)
{
r=r+i.format()+"\n";
}
for(SimpleLineItem j:simpleItems)
{
r=r+j.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue()
{
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
for(SimpleLineItem j:simpleItems)
{
amountDue = amountDue + j.getPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
private ArrayList<SimpleLineItem> simpleItems;
}
Few more
public class LineItem
{
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice()
{
return theProduct.getPrice() *quantity;
}
public String format()
{
return String.format("%'-30s%'8.2f%'5d%'8.2f", theProduct.getDescription(),theProduct.getPrice(),quantity,getTotalPrice());
}
private int quantity;
private Product theProduct;
}
Another one
public class SimpleLineItem
{
public SimpleLineItem(Product aProduct)
{
theProduct=aProduct;
}
public double getPrice()
{
return theProduct.getPrice();
}
public String format()
{
return String.format("%-30s" +" " + "%8.2f",
theProduct.getDescription(), theProduct.getPrice());
}
private Product theProduct;
}
Two more
public class Product
{
public Product(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
private String description;
private double price;
}
Last one
public class Address
{
public Address(String aName, String aStreet, String aCity, String
aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format()
{
return name + "\n" + street + "\n" + city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
Maybe you can take a look at the javadocs by Oracle on System.out.format and DecimalFormat class
Formatting Numeric Print Output
So basically this happens when you cannot decide the total length of your number column until you print out everything. For this you will need to set the number column's length to the lengthiest number or in your case price length and justify right all the numbers. So you'll need to add all the numbers to an array and loop through them to find the lengthiest number.