Be kind, learning.
These are the classes I have: Employee, salaryworker, hourlyworker, PayrollTest
I need to be able to modify existing employee, but I need it to be able to tell the difference if its an hourly or salary worker as they have different inputs. I can find the employee by its id, but not how to modify it correctly. I'm lost on how to do this.
import java.util.*;
import java.lang.*;
public class PayrollTest {
//Array Lists for Hourly and Salary Workers.
public static hourlyworker hourlyEmp = new hourlyworker(null, 0, 0.0, 0.0, 0.0, 0, 0, 0);
public static ArrayList<hourlyworker> hourlyList = new ArrayList<hourlyworker>();
//(String name, int dependents, double annualSalary, int month, int day, int year) {
public static salaryworker salaryEmp = new salaryworker(null, 0, 0.0, 0, 0, 0);
public static ArrayList<salaryworker> salaryList = new ArrayList<salaryworker>();
//Arraylist Initializing
public static ArrayList emps = new ArrayList(); //<Employee>
//Initializing scanner for user input
public static Scanner scan = new Scanner(System.in);
//Fields needed for PayrollTest
private static char choice;
private static char typeChoice;
private static boolean switcher = true;
#SuppressWarnings("resource")
public static void main(String[] args) {
menuSelection();
System.out.println();
}
#SuppressWarnings("unchecked")
private static void loadHourlyEmployee() {
System.out.println("\nEnter full name, number of dependents, hourly rate, regular hours worked, overtime worked, and date hired (yyyy mm dd)");
System.out.println("[one field per line, except date hired]: ");
hourlyEmp = new hourlyworker(null, 0, 0.0, 0.0, 0.0, 0, 0, 0);
hourlyEmp.setName(scan.nextLine());
hourlyEmp.setDependents(scan.nextInt());
hourlyEmp.setPayrate(scan.nextDouble());
hourlyEmp.setHours(scan.nextDouble());
hourlyEmp.setOvertimeHours(scan.nextDouble());
hourlyEmp.setHireDay(scan.nextInt());
emps.add(hourlyEmp);
System.out.println("\nYou entered an employee type for non-exempt: hourly.");
}
#SuppressWarnings("unchecked")
private static void loadSalaryEmployee() {
System.out.println("\nEnter full name, number of dependents, annual salary, and date hired (yyyy mm dd)");
System.out.println("[one field per line, except date hired]: ");
salaryEmp = new salaryworker(null, 0, 0.0, 0, 0, 0);
salaryEmp.setName(scan.nextLine());
salaryEmp.setDependents(scan.nextInt());
salaryEmp.setAnnualSalary(scan.nextDouble());
salaryEmp.setHireDay(scan.nextInt());
emps.add(salaryEmp);
System.out.println("\nYou entered an employee type for exempt: salary.");
}
private static void menuSelection() {
do {
System.out.println("\n\n\tEmployee Database");
System.out.println("\nEmployee Info Menu");
System.out.println("\tEnter L to (L)oad Employee info");
System.out.println("\tEnter M to (M)odify Employee info");
System.out.println("\tEnter P to (P)rint Employee info");
System.out.println("\tEnter Q to quit");
System.out.print("Please enter your choice: ");
choice = scan.nextLine().toUpperCase().charAt(0);
//Choice validation
while ((choice != 'L') && (choice != 'M') && (choice != 'P') && (choice != 'Q')) {
System.out.println("Invalid choice! Please select (L)oad, (M)odify, (P)rint, or (Q)uit: ");
choice = scan.nextLine().toUpperCase().charAt(0);
}
//Switch Statement
switch (choice) {
case 'L' :
System.out.println("What is the employee type? S = salary H = hourly ");
System.out.print("\n[Please enter letter] : ");
typeChoice = scan.nextLine().toUpperCase().charAt(0);
//typeChoice validation
while ((typeChoice != 'S') && (typeChoice != 'H')) {
System.out.println("Invalid choice! Please select (S)alary, (H)ourly: ");
typeChoice = scan.nextLine().toUpperCase().charAt(0);
}
if (typeChoice == 'H') {
loadHourlyEmployee();}
else if (typeChoice == 'S') {
loadSalaryEmployee();
}
break;
case 'M' :
modifyEmployee();
break;
case 'P' :
printEmployees();
break;
case 'Q' :
switcher = false;
System.out.println("\nProgram Terminated.");
break;
}
}
while (switcher != false);
}
private static void printEmployees() {
System.out.println("\nThere are " + emps.size() + " people in this database.\n");
for (int i = 0; i < emps.size(); i++) {
System.out.println(emps.get(i));
}
System.out.println("\nTotal = " + emps.size());
}
private static void modifyEmployee() {
System.out.print("Employee id#? ");
int findID = scan.nextInt();
boolean found = false;
int index = 0;
boolean deleteMod = false;
int index1 = 0;
while (index < emps.size() && !found) {
if (emps.get(index) != null) {
found = true;
}
deleteMod = true;
System.out.println("\nCurrent Info: ");
}
}
}
Use instanceof to determine if it is the class you want or not.
if (emps.get(index) instanceof hourlyworker) {
// code for hourlyworker
} else {
// code for salaryworker
}
The instanceof operator in java will help you here. As you are in learning mode, I will prefer you find out about it, rather than me explaining here.
Related
I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}
Im using Java and mySql
I have already done my code to prompt user to enter a date in the format DDMMYY and then store the info into the database, however, when i enter a valid date such as 121221, it will say "invalid date, please re-enter" Im not sure whats the problem..
this is my validation class
public class Validation {
public static boolean isValidDate(String date) {
String day = date.substring(0,2);
String month = date.substring(2,4);
String year = date.substring(4,6);
int i = Integer.parseInt(day);
int j = Integer.parseInt(year);
int k = Integer.parseInt(month);
if (k%2 !=0 || k == 8 || k == 10 || k == 12) {
if(i<=0 || i>31) {
return false;
}
}else if (k == 2) {
if(i<=0 || i>28) {
return false;
}
}else if (k%2 == 0 || k == 9 || k == 11) {
if (i<=0 || i>30) {
return false;
}
}
if(j<22 || j>100) {
return false;
}
return true;
}
public boolean isValidTransactionId(int transactionId) {
return true;
}
}
my UI class
package view;
import java.util.*;
import java.text.*;
import controller.DBController;
import controller.Validation;
import model.Transaction;
import model.Member;
public class UserInterface {
DBController db;
Validation vd;
Scanner scan;
Random rand;
String date;
boolean invalid;
int menuChoice, memberChoice;
Transaction transaction;
public UserInterface()throws Exception{
db= new DBController();
scan = new Scanner(System.in);
rand = new Random();
transaction = new Transaction();
}
public void MainMenu()throws Exception {
System.out.println("Welcome to SuperFun Theme Park!");
do {
System.out.print("Main Menu\n");
System.out.println("1. New Ticket Transaction");
System.out.println("2. Modify a Ticket Transaction");
System.out.println("3. Delete a Ticket Transaction");
System.out.println("4. View Ticket Transactions");
System.out.println("5. Exit");
System.out.print("Enter a number (1-5): ");
menuChoice = scan.nextInt();
scan.nextLine();
switch(menuChoice) {
case 1: newTicket(); break;
case 2: modifyTicket(); break;
case 3: deleteTicket(); break;
case 4: viewAllTransactions(); break;
case 5: System.out.println("Thank you. Have a nice day!"); break;
default: System.out.println("Invalid input. Please re-enter.\n");break;
}
}while(menuChoice!=5);
}
public void dateInput()throws Exception{
do {
if(menuChoice ==1 ) {
System.out.print("Enter ticket date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}else if (menuChoice == 4) {
System.out.print("Enter start date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}
invalid = false;
if(!vd.isValidDate(date)) {
invalid = true;
}else
invalid = false;
}while(invalid);
}
public void displayMemberInfo()throws Exception{
String result[] = null;
System.out.printf("\n%s %17s %20s\n","Index","Name", "Phone Number");
result = db.retrieveMemberInfo();
for(String temp: result)
System.out.println(temp);
}
public void newTicket() throws Exception{
int member=0, numOfMemberTickets=0, transactionId =0;
int memberTicket=80, nonMemberTicket=100, total=0, num=0;
boolean full = false, repeat= false;
//auto generate transaction id //100-200
int upperbound = 200;
int lowerbound = 100;
do {
transactionId = rand.nextInt(upperbound - lowerbound)+ lowerbound;
transaction.setId(transactionId);
}while(db.idExists(transaction.getId()));
//display transaction id
System.out.println("\nTransaction Id: " + transaction.getId());
//prompt user to enter ticket date
//validation for date
do {
dateInput();
db.maximumTicket(transaction.getDate());
if(db.sum>=100) {
System.out.println("Tickets are fully booked for the day. Please re-enter date.\n");
full = true;
}else {
System.out.printf("Number of tickets left for %s are %d\n" , date, 100-db.sum);
full = false;
}
}while(full);
//ask for total number of tickets then ask for members tickets
do {
System.out.print("Enter number of ticket(s) wanted: ");
num = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(num);
if(transaction.getTicketNum() > 100-db.sum)
System.out.println("Number of ticket(s) wanted exceeded availability. Please re-enter. ");
}while(transaction.getTicketNum() > 100-db.sum);
//if member, must choose which member
//loop through member info for validation
do {
repeat=false;
do {
System.out.print("Are there ticket(s) for member(s)? (1-yes 2-no): ");
member = scan.nextInt();
scan.nextLine();
if(member !=1 && member !=2)
System.out.println("Invalid input. Please re-enter.");
}while(member !=1 && member !=2);
if(member==1) {
do {
System.out.print("Enter the number of member tickets: ");
numOfMemberTickets = scan.nextInt();
scan.nextLine();
if(numOfMemberTickets<=0)
System.out.println("Invalid number of tickets. Please re-enter.");
}while(numOfMemberTickets<=0);
//display member info table
displayMemberInfo();
for(int cnt=0; cnt<numOfMemberTickets; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
// if(db.memberExists(transaction.getId())) {
// System.out.println("Member are only allowed to purchase one ticket in a day. Please re-enter.");
// repeat = true;
// }else
db.insertNumber(memberChoice, transaction.getId());
}while(memberChoice<=0);
}
}
}while(repeat);
//calculate and display total price
total = (numOfMemberTickets * memberTicket) + (Math.abs((transaction.getTicketNum() - numOfMemberTickets)) * nonMemberTicket);
transaction.setTotal(total);
System.out.println("Total price: RM" + transaction.getTotal());
//save data into database
boolean success = db.insertInfo(transaction.getDate(), transaction.getId(), transaction.getTicketNum(), transaction.getTotal());
if(success)
System.out.println("Transaction record inserted successfully.\n");
else
System.out.println("Error in inserting record.\n");
}
public void modifyTicket() throws Exception{
int transactionId=0, newTicketNum=0, newNumOfMemberTicket=0, newTotal=0, change=0;
String newDate="";
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
transaction.setId(transactionId);
if(!db.idExists(transaction.getId()))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transaction.getId()));
//display details
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transaction.getId());
//user can edit date, number and members' phone number
System.out.print("\nEnter new ticket date: ");
newDate = scan.nextLine();
transaction.setDate(newDate);
System.out.print("Enter new number of tickets(including members' tickets): ");
newTicketNum = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(newTicketNum);
System.out.print("Enter new number of member ticket(s): ");
newNumOfMemberTicket = scan.nextInt();
scan.nextLine();
System.out.print("Is there a change in member(s)? (1-yes 2-no): ");
change = scan.nextInt();
scan.nextLine();
if(change==1) {
displayMemberInfo();
for(int cnt=0; cnt<newNumOfMemberTicket; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
db.updateNumber(memberChoice, transactionId);
}while(memberChoice<=0);
}
}
//recalculate total price
newTotal = (newNumOfMemberTicket * 80) + (Math.abs(newTicketNum - newNumOfMemberTicket)* 100);
transaction.setTotal(newTotal);
//update database
boolean success = db.updateInfo(transaction.getDate(), transaction.getTicketNum(), transaction.getTotal(), transaction.getId());
if(success)
System.out.println("Information updated successfully.\n");
else
System.out.println("Error in updating information.\n");
}
public void deleteTicket()throws Exception{
int transactionId=0, choice =0;
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
if(!db.idExists(transactionId))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transactionId));
transaction.setId(transactionId);
//display all information of that transaction
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transactionId);
//re-confirm whether to delete
do {
System.out.print("\nConfirm delete? (1-yes 2-no): ");
choice = scan.nextInt();
}while(choice !=1 && choice !=2);
//delete from database
if(choice == 1) {
boolean success = db.deleteInfo(transaction.getId());
if (success)
System.out.println("Transaction Info deleted successfully.\n");
else
System.out.println("Error in deleting transaction info.\n");
}else
System.out.println("Returning to main menu...\n");
}
public void viewAllTransactions() throws Exception{
String result[] = null;
String date2 ="", letter="";
//enter start date
dateInput();
switch(date.substring(2,4)) {
case "01": letter = "Jan"; break;
case "02": letter = "Feb"; break;
case "03": letter = "Mar"; break;
case "04": letter = "Apr"; break;
case "05": letter = "May"; break;
case "06": letter = "June"; break;
case "07": letter = "July"; break;
case "08": letter = "Aug"; break;
case "09": letter = "Sep"; break;
case "10": letter = "Oct"; break;
case "11": letter = "Nov"; break;
case "12": letter = "Dec"; break;
}
date2 = date.substring(0,2) + letter + "20" + date.substring(4,6);
//show all records from start date
//display error if no matching one
boolean success = db.matchingDate(transaction.getDate());
if(success) {
System.out.println("\nTransaction Report from " + date2);
System.out.printf("%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
result = db.retrieveAllInfo(date);
for(String temp: result)
System.out.println(temp);
}else
System.out.println("Error in finding date entered.");
System.out.println("\nReturning to main menu...\n");
}
}
transaction class
public void setDate(String date) {
if(Validation.isValidDate(date))
this.date = date;
else
System.out.println("Date is invalid. Please re-enter.");
}
Honestly, those if checks are kind of hard to look at. Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class dateTime {
public static void main(String[] args) throws ParseException {
SimpleDateFormat datefr = new SimpleDateFormat("dd-MM-yy");
datefr.setTimeZone(TimeZone.getTimeZone("UTC"));
datefr.setLenient(false);
try {
Date date = datefr.parse("12-10-21");
System.out.println(true);
} catch (ParseException e) {
System.out.println(false);
System.out.println(e.getMessage());
}
}
}
public class Attraction {
String description;
private String contactDetails;
private String guide;
private String rating;
private final double noTicketsSold = 0;
private int maxGroupSize;
private int amountActivities;
private double ticketCost;
private int uniqueID;
private static int count;
private char chosen;
private String[] storedActivities;
private static int id_counter = 0;
private final int MAX_NUM_ATTRACTIONS = 5;
private static int[] attractions;
public Attraction(int MAX_NUM_ATTRACTIONS) {
id_counter++;
attractions = new int[MAX_NUM_ATTRACTIONS];
count = 0;
}
public int getUniqueID() {
return this.uniqueID;
}
public void recordAttraction() {
if (count == attractions.length) {
System.out.println("Attractions are full");
return;
}
if (count < attractions.length) {
attractions[count] =
count++;
}
}
public Attraction(char chosen, String description, double ticketCost, int maxGroupSize, String contactDetails,
int amountActivities, String[] storedActivities) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.maxGroupSize = maxGroupSize;
this.contactDetails = contactDetails;
this.amountActivities = amountActivities;
this.storedActivities = storedActivities;
}
public Attraction(char chosen, String description, double ticketCost, String guide, String rating) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.guide = guide;
this.rating = rating;
}
public void displayAllDetails() {
System.out.printf("\nID : %d%n", getUniqueID());
System.out.printf("Description : %s%n", description);
System.out.printf("Ticket cost : $%.2f%n", ticketCost);
System.out.printf("Tickets sold : %.0f%n", noTicketsSold);
if (chosen == 'y') {
System.out.println("Activity :");
int i = 0;
while (amountActivities > i) {
System.out.println(" : " + storedActivities[i]);
i++;
}
System.out.printf("Max Attendees : %d%n", maxGroupSize);
System.out.printf("Agency : %s%n", contactDetails);
}
if (chosen == 'n') {
System.out.printf("Instruction guide : %s%n", guide);
System.out.printf("Difficulty : %s%n", rating);
}
}
}
import java.util.Scanner;
public class StageA {
private static final Scanner sc = new Scanner(System.in);
private Attraction attractions = null;
public static void main(String[] args) {
StageA a = new StageA();
a.runMenu();
}
private void runMenu() {
char selection;
do {
displayMenu();
selection = sc.nextLine().toLowerCase().charAt(0);
processSelection(selection);
} while (selection != 'x');
}
private void displayMenu() {
System.out.println("\n **** Ozzey Attraction Menu ****");
System.out.println("A : Add New Attraction");
System.out.println("B : View Attraction");
System.out.println("C : List All Attractions");
System.out.println("D : Sell Ticket");
System.out.println("E : Refund Ticket");
System.out.println("F : Remove Attraction");
System.out.println("X : Exit\n\n");
System.out.printf("Enter selection : ");
}
private void createAttraction() {
String description;
double ticketCost;
char chosen;
int maxGroupSize;
String contactDetails;
int amountActivities;
System.out.print("\nEnter attraction description : ");
description = sc.nextLine();
System.out.print("Enter cost of a Ticket : ");
ticketCost = Double.parseDouble(sc.nextLine());
System.out.println("Is this a supervised tour ? [Y/N] :");
chosen = sc.nextLine().toLowerCase().charAt(0);
switch (chosen) {
case 'y':
System.out.println("What is maximum permitted tour group size?");
maxGroupSize = Integer.parseInt(sc.nextLine());
System.out.println("Enter the agency contact details: ");
contactDetails = sc.nextLine();
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
while (amountActivities < 1) {
System.out.println("Please enter valid number of activities great than zero");
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
}
String[] storedActivities = new String[amountActivities];
int counter = 0;
while (amountActivities > counter) {
System.out.printf("Please enter activity #%d: ", counter);
storedActivities[counter] = sc.nextLine();
counter++;
}
attractions = new Attraction(chosen, description, ticketCost, maxGroupSize, contactDetails,
amountActivities, storedActivities);
break;
case 'n':
String guide;
String rating;
System.out.printf("Enter the instruction guide:\n");
guide = sc.nextLine();
System.out.printf("Enter the difficulty rating:\n");
rating = sc.nextLine();
attractions = new Attraction(chosen, description, ticketCost, guide, rating);
break;
default:
System.out.print("Please Enter valid answer ");
System.out.println("Is this a supervised tour ? [Y/N] :");
}
}
private void processSelection(char selection) {
switch (selection) {
case 'a':
attractions.recordAttraction();
createAttraction();
break;
case 'b':
System.out.printf("b");
break;
case 'c':
System.out.printf("c");
break;
case 'd':
System.out.printf("d");
break;
case 'e':
System.out.printf("e");
break;
case 'f':
System.out.printf("f");
break;
case 'x':
System.out.println("Good Bye!");
break;
default:
System.out.println("Invalid input, try again\n");
}
}
Hi all i stuck a part of my project for school i have to create a single array in my Attraction class called int[] attractions that can have a max of 5 stored createAttraction() from my stageA class.
When they choose 'a' in my switch statement this were i add createAttraction(); when user has created five attraction in will then tell the user its full and no more can be added. i tried a couple of things but i stuck any help wont be appreciated.
Note: this is the way project has to be setup.
Here are few things you should change in your code :
Change the constructor in attractions class, since you have already set final variable as 5 and if it is fixed, you do not need constructor with parameter: MAX_NUM_ATTRACTIONS
You need to initialise attraction object in StageA class :
private Attraction attractions = null; => private Attraction attractions = new Attraction()
Decide when you want to increment counter variable, when you dorecordAttraction or actually creating one and count should be checked greater or equal to attractions length/ MAX_NUM_ATTRACTIONS
return a value from method record Attraction to decide if you have to proceed with createAttraction or not
guys, am doing java programing and try to make a list, but i cannnot let it work as i expected, please help me find out where is wrong.
i have create the code on BlueJ and try to make main and method in different part, but when i try to add a variable in list, it seems added but wont present correctly, and remove method will call error and shut down the whole program
one is :
import java.util.ArrayList;
public class Plane
{
//Create 3 types of variables.
private String name;
private int safelength;
private short station;
private String passengername;
private static int seat;
private static int age;
private ArrayList<Passenger> Passengers;
public Plane(String psgname, int psgseat, int psgage)
{
psgname = passengername;
psgseat = seat;
psgage = age;
Passengers = new ArrayList<Passenger>();
}
public Plane(String planename, int maxlength, short astation)
{
name = planename;
safelength = maxlength;
station = astation;
}
public void addPassenger(Passenger Passenger)
{
Passengers.add(Passenger);
}
public void addPassenger(String passengernames, int pseat, int page)
{
Passengers.add(new Passenger(passengername, seat, page));
}
public Passenger findPassenger(String find)
{
for(Passenger ps : Passengers)
{
if(ps.getpname().contains(find))
{
return ps;
}
}
return null;
}
public int numberofPassenger()
{
return Passengers.size();
}
public void removePassenger(int number)
{
if (number >= 0 && number <numberofPassenger())
{
Passengers.remove(number);
}
}
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
public void setname(String n)
{
name = n;
}
public String getname()
{
return name;
}
public void setsafelength(int s)
{
safelength = s;
}
public int getsafelength()
{
return safelength;
}
public void setstation(short a)
{
station = a;
}
public short getstation()
{
return station;
}
public String toString()
{
String text = "System checked, " + getname() + ", you can prepare yourself at station " + getstation() + " with the maxlength of " + getsafelength() + " metres.";
return text;
}
}
another one is :
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private static String pname;
private static int seat;
private static int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(pname, seat, age);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public static void setpname(String pn)
{
pname = pn;
}
public static String getpname()
{
return pname;
}
}
Problem 1.
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
Here you are printing the value of instance variable,not the passenger's name.To print it, do
System.out.println(Passengers.get(index).getpname());
but this will return null,because your pname is static and you have never initialized its value.For this,change all yor static varibales to non-static.
Problem 2.
Passenger padd = new Passenger(pname, seat, age);
you are storing passenger's name seat age in x y zvariables respectively,butduring the creation of Passenger ,you are using pname seat age variables, which are null.So here do
Passenger padd = new Passenger(x, y, z);
At last,change every static variable and methods to non-static.
Final Solution will look like this,
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private String pname;
private int seat;
private int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(x, y, z);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public void setpname(String pn)
{
pname = pn;
}
public String getpname()
{
return pname;
}
}
I am trying to get my program to exception handle for if the user inputs nothing so they will get an error message of "Error, enter a dollar amount greater than 0" or "Error, Enter a 1, 2 or 3". As of now, the program does nothing if the user just hits "enter" with no input....
import java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Candleline
{
public static void main(String[] args)
{
//initiate scanner
Scanner input = new Scanner(System.in);
System.out.println("\tCandleLine - Candles Online");
System.out.println(" ");
//declare variables and call methods
double candleCost = getCandleCost();
int shippingType = getShippingType();
double shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandleCost()
{
//get candle cost and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
double candleCost = 0;
while(!done)
{
System.out.print("Enter the cost of the candle order: ");
try
{
inputCost = input.next();
candleCost = Double.parseDouble(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (candleCost <=0) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
}
return candleCost;
}
public static int getShippingType()
{
//get shipping type and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
int shippingCost = 0;
while(!done)
{
System.out.println(" ");
System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: ");
try
{
inputCost = input.next();
shippingCost = Integer.parseInt(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println(" ");
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
}
return shippingCost;
}
public static double getShippingCost(double candleCost, int shippingType)
{
//calculate shipping costs
double shippingCost = 0;
if (shippingType == 1)
{
shippingCost = 16.95;
}
if (shippingType == 2)
{
shippingCost = 13.95;
}
if (shippingType == 3)
{
shippingCost = 7.95;
}
if (candleCost >= 100 && shippingType == 3)
{
shippingCost = 0;
}
return shippingCost;
}
public static void output(double fCandleCost, double fShippingCost)
{
//display the candle cost, shipping cost, and total
Scanner input = new Scanner(System.in);
DecimalFormat currency = new DecimalFormat("$#,###.00");
System.out.println("");
System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost));
}
}
Replace input.next();
with input.nextLine();
You can write a method that validates the input before proceeding. It can keep asking for inputs if user enters something that is not valid. E.g. below example demonstrates how to validate an integer input:
private static int getInput(){
System.out.print("Enter amount :");
Scanner scanner = new Scanner(System.in);
int amount;
while(true){
if(scanner.hasNextInt()){
amount = scanner.nextInt();
break;
}else{
System.out.println("Invalid amount, enter again.");
scanner.next();
}
}
scanner.close();
return amount;
}