This is super class of all,Employee class.
import java.util.Scanner;
import java.util.Calendar;
import java.util.*;
class Employee {
Scanner in = new Scanner(System.in);
Calendar cal = Calendar.getInstance();
String name;
String number;
int month;
int week;
double pay;
void load() {
System.out.println("Enter name of employee");
name = in.nextLine();
System.out.println("Enter social security number");
number = in.nextLine();
System.out.println("Enter employee's birthday month(1-12)");
month = in.nextInt();
System.out.println("Enter employee's birthday week(1-4)");
week = in.nextInt();
}
public String toString() {
return "employee : " + name + " social security number : " + number
+ " paycheck : $" + pay;
}
void getBonus() {
int mont = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
if (month == mont + 1 && week == (day / 7) + 1)
pay = pay + 100;
}
}
This is subclass of employee .
import java.util.Scanner;
class Hourly extends Employee {
Scanner in = new Scanner(System.in);
double pay;
int hpay;
int hours;
void load() {
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
double getEarnings() {
if (hours > 40)
pay = 1.5 * (hours - 40) * hpay + hpay * 40;
else
pay = hpay * hours;
return pay;
}
}
There are 2 more subclasses like these and finally i have test file.
import java.util.Scanner;
class driver {
public static void main(String args[]) {
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out
.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
if (b == 1) {
Hourly h = new Hourly();
h.super.load();// error cannot find symbol h
h.load();
h.getEarnings();
}
if (b == 2) {
Salaried s = new Salaried();
s.load();
s.getEarnings();
}
if (b == 3) {
Salariedpluscommision sp = new Salariedpluscommision();
sp.super();// error that super should be in first line but then
// where can i define sp
sp.super.load();// cannot find symbol sp
sp.load();
sp.getEarnings();
}
}
}
}
I have got 3 errors in these codes and as i am beginner i don't know how can i solve these errors.
My program takes the employee's details from user and calculate paycheck of that employee.
Also,I am confused in how can i print all employee's paychecks at last after user have completed giving input of all employee's details.Can i do these with an array ?
But first,i have to remove these errors and also suggest my which topics are weak which i should focus more.
Thank you in advance
You appear to be a bit confused about the keyword super.
In the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.super();//error that super should be in first line but then where can i define sp
sp.super.load();//cannot find symbol sp
sp.load();
sp.getEarnings();
the compiler is telling you that super cannot be used where you're using it.
Most likely you just don't need it at all in the driver code and the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.load();
sp.getEarnings();
will do what you thought you needed these calls for.
Similarly, in the earlier code, you can likely just delete the line
h.super.load();// error cannot find symbol h
As it's coded however, you might need to call some superclass methods from your subclasses, which is what the keyword is for.
In Hourly and likely the other subclasses, you probably want to call the Employee load method within the subclass load method:
void load(){
super.load();
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
which appears to be what you were trying for with some of the non-compiling code in driver.
Several suggestions:
Make Employee an abstract class and add public abstract getEarnings(); method
Simplify your Driver routine to use switch / case rather than multiple if statements
Create an ArrayList to collect a list of all employees
Use the "type" of employee to create the right kind ... use the same variable name though
After creating the "right kind" of employee, load it and get the earnings
.... (print out the earnings?
Just create objects .. don't use "super
Consider the following for Driver:
import java.util.ArrayList;
import java.util.Scanner;
class driver {
public static void main(String args[]) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee emp;
double earnings;
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
emp = null;
switch (b) {
case 1:
emp = new Hourly();
break;
case 2:
emp = new Salaried();
break;
case 3:
emp = new Salariedpluscommision();
break;
default:
System.out.println("You entered an invalid employee type.");
break;
}
if (emp != null) {
emp.load();
earnings = emp.getEarnings();
employees.add(emp);
System.out.println("Earnings are: " + earnings + "for " + emp.getName());
}
Related
I have written a code that takes input as Account details and displays the details by using ArrayList. I however want the list to fetch a particular/specific account details only for a data. Lets say i stored account number details for 127783 and 127784. Now i want only account number 127783 details. How do i fetch that using arrayList. If it doesn't happen with an ArrayList then what to use.
package com.techlabs.account;
import java.util.ArrayList;
import java.util.Scanner;
public class AccountMenu {
static int accountno;
String name;
double balance;
ArrayList a = new ArrayList();
public AccountMenu() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
if (number == 1) {
System.out.println("Enter the Account no.");
accountno = in.nextInt();
a.add(accountno);
System.out.println("Enter the name");
name = in.next();
a.add(name);
System.out.println("Enter the Balance");
balance = in.nextDouble();
a.add(balance);
}
if (number == 2) {
System.out.println("Account details are :");
for (Object b : a) {
System.out.println(b);
}
}
if (number == 3) {
System.out.println("Enter the account number");
accountno=in.nextInt();
if (a.contains(accountno)) {
System.out.println(a);
}
}
if (number == 4) {
System.out.println("Exit");
}
System.out.println("Enter the option :1. Open Account 2. Show Account details 3.Retrieve details by Searching Account Number and 4. Exit again");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu am = new AccountMenu();
}
}
Instead of dropping everything into a list of objects I would create a class for storing account details (with members of account number, name, balance).
I would store these in a Map < Integer, Account >. When you need a specific account's detail you can say map.get(accountNumber) and you will get back your specific Account instance.
Edit:
A wrapper class to hold Account details:
public Class AccountDetails{
public final int accountNumber;
public final String name;
public final int balance;
constructor
}
Instead of arraylist a should be:
Map<Integer, AccountDetails> a = new HashMap<>();
Where your create new accounts:
AccountDetails accountDetails = new AccountDetails(accountno, name, balance);
a.put(accountno, accountDetails)
Where you print details you should ask for the account number from the user, and after that:
System.out.println(a.get(accountno));
Of course to see something meaningful you should write a toString() method for the AccountDetails class.
I found a lot of errors relatying to POO in your code. Please check the code below and study OO concepts. I created a private class to represent the accounts. That way you can have an arraylist of account objects.
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication5 {
private static final class Account {
int accountno;
String name;
double balance;
#Override
public String toString() {
return "Account{" + "accountno=" + accountno + ", name=" + name + ", balance=" + balance + '}';
}
public void deposit(double amount){
balance = balance + amount;
}
void withdraw(double amount){
balance = balance-amount;
}
}
public static void AccountMenu() {
ArrayList<Account> a = new ArrayList();
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
switch (number) {
case 1: {
Account c = new Account();
System.out.println("Enter the Account no.");
c.accountno = in.nextInt();
System.out.println("Enter the name");
c.name = in.next();
System.out.println("Enter the Balance");
c.balance = in.nextDouble();
a.add(c);
break;
}
case 2: {
System.out.println("Account details are :");
for (Account b : a) {
System.out.println(b);
}
break;
}
case 3: {
System.out.println("Enter the account number");
int accountno = in.nextInt();
for (Account account : a) {
if (account.accountno == accountno) {
System.out.println(account);
}
}
break;
}
case 4:
System.out.println("Exit");
}
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu();
}
}
I'm writing a driver class for a piggy bank class that I created. The idea is that it is supposed to add different types of coins (user input) and then total the cents and display them until "X" is input by the user. I think I have the code right, but there is a weird issue where if I use the "countMoney" accessor into the code, it tells me that all of my variables in the driver class are uninitialized. If I remove it, there are no errors shown by Eclipse. I've printed my source and driver class below:
package piggy;
/**
* #author Kevin
*
*/
import java.util.Scanner;
import piggy.PiggyBank;
public class PiggyBankTester {
/**
* #param args
*/
public static void main(String[] args) {
String num = "str", num1;
int count = 0;
int money;
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
PiggyBank total = new PiggyBank();
System.out.println("Welcome to the Piggy Bank Tester");
System.out.println("What type of coin to add (Q, H, D or X to exit)?");
num1 = scan.nextLine();
num = num1.toUpperCase();
{
if (num.equals("X"))
System.out.println("Goodbye.");
else if (num != "X")
{
System.out.println("How many do you wish to add?");
count = scan.nextInt();
if (num.equals("Q"))
total.addQuarters(count);
else if (num.equals("H"))
total.addHalfDollars(count);
else if (num.equals("D"))
total.addDollars(count);
else if (num.equals("X"))
System.out.println("Goodbye.");
}
}
{
total.calculate();
money = total.countMoney();
System.out.println("The piggy bank now contains " + money + " cents.");
}
}
}
You don't need (String Q,D,H,X) .
Also you have declared this variables without give them any value just name.
A way you can do it is to change your if-else statements and set , for example if you want num to be equal to Q ---> if (num.equals("Q") ) <---
I'm having a bit of problem with the getCost method in this code (I'll paste it below) and really need a response as soon as possible since this is due by midnight tomorrow. So the problem is that it says the things on the other side of the == are not valid, I mean the GRO, Gro, gro, SAL, Sal, and sal. For this code I have as user input a destination. Then I calculate the travel cost based on this input, and I'm also supposed to provide a free child ticket for every adult ticket, but I'm not sure how to do that at all. I'm sure what to do with the second method at all but it's required for the project so it has to be there. Thanks for any and all help.
import java.util.*;
public class HolidayTravel {
public static void main (String[] args) {
System.out.println("Thank you for choosing the Holiday Travel Special!");
System.out.println("All trips depart from and return to Raleigh, NC, and");
System.out.println("must take place between Nov 1, 2014 and Jan 15, 2015.");
System.out.println("When prompted, please enter your destination:");
System.out.println("GRO (Greensboro), SAL (Salisbury), or CLT (Charlotte),");
System.out.println("your departure/return dates, and the number of adult,");
System.out.println("student, and child ticketes you would like to purchase.");
System.out.println("Destination (GRO, SAL, CLT): ");
Scanner dest = new Scanner(System.in);
String destination = dest.nextLine();
System.out.println("Departure month (11, 12, 1): ");
Scanner mth = new Scanner(System.in);
int departureMonth = mth.nextInt();
System.out.println("Departure Day: ");
Scanner d = new Scanner(System.in);
int departureDay = d.nextInt();
System.out.println("Return month (11, 12, 1): ");
Scanner rM = new Scanner(System.in);
int returnMonth = rM.nextInt();
System.out.println("Return Day: ");
Scanner rD = new Scanner(System.in);
int returnDay = rD.nextInt();
System.out.println("Number of Adult Tickets: ");
Scanner aT = new Scanner(System.in);
int numberOfAdultTickets = d.nextInt();
System.out.println("Number of Student Tickets: ");
Scanner sT = new Scanner(System.in);
int numberOfStudentTickets = d.nextInt();
System.out.println("Number of Child Tickets: ");
Scanner cT = new Scanner(System.in);
int numberOfChildTickets = d.nextInt();
System.out.printf("Cost of tickts: %f\n", getCost (destination, numberOfAdultTickets, numberOfStudentTickets, numberOfChildTickets));
}
//Return true if the departure/return dates are valid dates between Nov 1 and Jan 15
//and the departure date occurs before or is the same as the return date
//Return false otherwise
//public static boolean areValidDates (int departureMonth, int departureDay, int returnMonth, int returnDay){
//}
//Calculates and returns cost of tickets based on destination, price of adult and child tickets,
//student discount, and with one free child ticket for each adult ticket purchase
//Throws an IllegalArgumentException if destination is invalid or number of tickets < 0
public static int getCost (String destination, int numberOfAdultTickets, int numberOfStudentTickets, int numberOfChildTickets) {
if (destination == GRO || Gro || gro){
double gCost = (numberOfAdultTickets*30.00) + (numberOfStudentTickets*(30.00-5.00)) + (numberOfChildTickets*20);
}else if(destination == SAL || Sal || sal){
double sCost = (numberOfAdultTickets*55.00) + (numberOfStudentTickets*(55.00-5.00)) + (numberOfChildTickets*45);
}else{
double cCost = (numberOfAdultTickets*60.00) + (numberOfStudentTickets*(60.00-5.00)) + (numberOfChildTickets*50);
}
}
}
You have to do your comparison like this:
public static int getCost (String destination, int numberOfAdultTickets, int numberOfStudentTickets, int numberOfChildTickets) {
if (destination.equals(GRO) || destination.equals(Gro) || destination.equals(gro)){
double gCost = (numberOfAdultTickets*30.00) + (numberOfStudentTickets*(30.00-5.00)) + (numberOfChildTickets*20);
}else if(destination.equals(SAL) || destination.equals(Sal) || destination.equals(sal)){
double sCost = (numberOfAdultTickets*55.00) + (numberOfStudentTickets*(55.00-5.00)) + (numberOfChildTickets*45);
}else{
double cCost = (numberOfAdultTickets*60.00) + (numberOfStudentTickets*(60.00-5.00)) + (numberOfChildTickets*50);
}
I hope GRO, Gro, gro, SAL, Sal and sal are variables of the type String. If not put "" between them, like this: "GRO" and so on...
I am currently trying to program a array based program. We have to make a employee class then a tester main class that holds a array of five user input employee names, salaries, and performance rating. The performance rating is used to determine a supplied raise amount. I have it basically done, but when i run the program, nothing happens even though java virtual machine is running. I have looked up and down for the error, anyone can point out what i am doing wrong?
Employee Class
public class Employee
{
private String employeeName;
private int salary;
private int performanceRating;
public Employee()
{
employeeName = "";
salary = 0;
performanceRating = 0;
}
public String getEmployeeName()
{
return employeeName;
}
public int getSalary()
{
return salary;
}
public int getPerformanceRating()
{
return performanceRating;
}
}
And this is the tester main class where the error comes in somewhere
import java.util.Scanner;
public class Tester
{
public static void main(String[] args)
{
Employee[] work = new Employee[5];
Scanner scanString = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
String employeeName = "";
double salary = 0;
double performanceRating = 0;
String choice = scanString.nextLine();
while(choice.equals("yes"))
{
for(int i = 0; i < 5 ;i++)
{
System.out.println("What is the employee's name?");
employeeName = scanString.nextLine();
System.out.println("Enter Employee's salary");
salary = scanInt.nextInt();
System.out.println("Performance? 1 = excellent, 2 = good, 3 = poor");
performanceRating = scanInt.nextInt();
work[i] = new Employee();
}
for(int j = 0; j < 5; j ++)
if(work[j].getPerformanceRating() == 1)
{
salary = salary * 0.06;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 2)
{
salary = salary * 0.04;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 3)
{
salary = salary * 0.015;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating < 5)
{
salary = salary;
System.out.println("Rating is off scale. No raise for emplyee " + employeeName);
}
System.out.println("Enter more employees? type 'yes' if you want to go again");
choice = scanString.nextLine();
}
System.out.println("Done");
}
}
The program reads from System.in. If you don't enter anything, nothing will happen.
Not sure why you have 2 Scanners instead of just one.
You have while(choice.equals("yes")) except you never prompt the user to make a choice. The program does do stuff (some of which may not all work properly), but you have to give the program input. What you can do is ask the user a question before the line String choice = scanString.nextLine();.
As a side note, you could use a switch in place of the if and else if's and it might be a little easier to read and understand.
I need to design and implement an application called CinemaPrice to determine how much a person pays to go the the cinema. The program should generate an age from 1 - 100 using the Random class and prompt the user for the full ticket price. Then display the appropriate ticket price using the currency format (an example in your book ). You may want to refer to the example we did together in class to help you with the "if statement". Decide ticket price on the following basis:
1. under 5, free;
2. aged 5 to 12, half price;
3. aged 13 to 54, full price;
4. aged 55, or over, free.
I would really like some help on this I'm new to java and been spending hours on this now I would love to finish it :)
This is what I have so far:
import java.util.Scanner; //Needed for the Scanner class
import java.util.Random;
import java.text.DecimalFormat;
public class CinemaPrice
{
public static void main(String[] args) //all the action happens here!
{ Scanner input = new Scanner (System.in);
int age = 0;
double priceNumber = 0.00;
Random generator = new Random();
age = generator.nextInt(100) + 1;
if ((age <= 5) || (age >=55) {
priceNumber = 0.0;
}else if (age <= 12){
priceNumber = 12.50;
}else {
system.out.println("Sorry, But the age supplied was invalid.");
}
if (priceNumber <= 0.0) {
System.out.println("The person age " + age + " is free!);
}
else {
System.out.println("Price for the person age " + age + "is: $" + priceNumber);
}
} //end of the main method
} // end of the class
I don't know how to prompt and read input from a user though - can you help?
The first issue that I see is that you need to update your conditional statement here as anything from 13 to 54 will be an invalid age...
if ((age <= 5) || (age >=55) {
priceNumber = 0.0;
}else if (age <= 12){
priceNumber = 12.50;
}else if (age < 55){
//whatever this ticket price is
}else {
system.out.println("Sorry, But the age supplied was invalid.");
}
Something like that would work...
You have stated that your real problem is getting data into your program, the following should demonstrate using the Scanner class
public static void main(String[] args) {
System.out.println("Enter an age");
Scanner scan=new Scanner(System.in);
int age=scan.nextInt();
System.out.println("Your age was " + age);
double price=scan.nextDouble();
System.out.println("Your price was " + price);
}
Now thats the basic idea, but if you provide an incorrect input (like a word) you can get an exception, you can however check that the input you're getting is correct and only accept it if its what you want, like this;
public class Main{
public static void main(String[] args) {
System.out.println("Enter an age");
Scanner scan=new Scanner(System.in);
while (!scan.hasNextInt()) { //ask if the scanner has "something we want"
System.out.println("Invalid age");
System.out.println("Enter an age");
scan.next(); //it doesn't have what we want, demand annother
}
int age = scan.nextInt(); //we finally got what we wanted, use it
System.out.println("Your age was " + age);
}
}