Using Scanner class to take user input for constructor Variables - java

I am trying to use a Scanner object to take in user input that will then be attributed to the following values for an object called TargetHeartRateCalculator.
TargetHeartRateCalculator takes constructor parameters of..
String fName, String lName, int month, int day, int year.
Normally without using the Scanner I would just instantiate the object with the parameters manually like...
TargetHeartRateCalculator patient1 = new TargetHeartRateCalculator("Tom", "Willickers", 01, 25, 1966);
I need to use the Scanner to take user input and then from the user recived input assign values to fName, lName, month, day, year.
I have tried making the object instantiation part of the assignment of the user input through the Scanner object by the syntax is not correct and I'm not even really sure if that's how your supposed to do something like this.
I feel like this is probably a simple solution but the answer is quite evasive to me.
Here is my Driver Class...
import java.util.Scanner;
public class DriverClass {
//--------------------------------------------------------------------------------------
// TARGET HEART RATE CALCULATOR CLASS FUNCTIONALITY TEST
//--------------------------------------------------------------------------------------
TargetHeartRateCalculator patient1 = new TargetHeartRateCalculator("Tom", "Willickers", 01, 25, 1966);
TargetHeartRateCalculator patient2 = new TargetHeartRateCalculator("Bill", "Skarsgard", 8,9, 1990);
//Write a java app that prompts for the persons information
//instantiates an object and prints the information from that object
//first name, last name, date of birth,
// calculates maximum heart rate, and target heart rate.
//and then displays them to the them.
Scanner input = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fnInput = input.nextDouble();
System.out.printf("%nThank you %s %s. Your date of birth is %n" +
"%d and you are %d years old!%n" +
"Your maximum heart rate is %.2f and your %n" +
"Target Heart Rate range is %.2f%n%n" get,
patientInfo(patient1);
patientInfo(patient2);
displayAgeYears(patient1);
displayAgeYears(patient2);
displayMaxHeartRate(patient1);
displayMaxHeartRate(patient2);
displayTargetHeartRate(patient1);
displayTargetHeartRate(patient2);
}
}
Here is my Class
import java.time.LocalDateTime;
public class TargetHeartRateCalculator {
private String fName;
private String lName;
private int dOB;
private int bMonth;
private int bDay;
private int bYear;
private int ageYears;
private double maxHeartRate;
private double lowTargetHearRate;
private double highTargetHearRate;
LocalDateTime now = LocalDateTime.now();
int cYear = now.getYear();
int cMonth = now.getMonthValue();
int cDay = now.getDayOfMonth();
//constructor
public TargetHeartRateCalculator(String fNameIn, String lNameIn, int monthIn, int dayIn, int yearIn) {
fName = fNameIn;
lName = lNameIn;
bMonth = monthIn;
bDay = dayIn;
bYear = yearIn;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public int getBMonth() {
return bMonth;
}
public void setBMonth(int month) {
this.bMonth = month;
}
public int getBDay() {
return bDay;
}
public void setBDay(int day) {
this.bDay = day;
}
public int getBYear() {
return bYear;
}
public void setBYear(int year) {
this.bYear = year;
}
public int getAgeYear(){
int currentAgeYear = cYear -bYear;
return currentAgeYear;
}
public int getAgeMonth(){
int currentAgeMonth =cMonth - bMonth;
return currentAgeMonth;
}
public int getAgeDay(){
int currentAgeDay =cDay - bDay;
return currentAgeDay;
}
public String getdOB(TargetHeartRateCalculator patient) {
String dOB = String.format("%s/%s/%s",
patient.getBMonth(), patient.getBDay(), patient.getBYear());
return dOB;
}
public void setdOB(int dOB) {
this.dOB = dOB;
}
public static String displayAgeYears(TargetHeartRateCalculator patient) {
String ageYears = String.format("%s %s is %s Years old",
patient. getfName(), patient.getlName(), patient.getAgeYear());
return ageYears;
}
public void setAgeYears(int ageYears) {
this.ageYears = ageYears;
}
public double getMaxHeartRate() {
double maxHeartRate = (220 - getAgeYear()) ;
return maxHeartRate;
}
public void setMaxHeartRate(int maxHeartRate) {
this.maxHeartRate = maxHeartRate;
}
public double getLowTargetHearRate() {
lowTargetHearRate = getMaxHeartRate() * .5;
return lowTargetHearRate;
}
public void setLowTargetHearRate(int lowTargetHearRate) {
this.lowTargetHearRate = lowTargetHearRate;
}
public double getHighTargetHeartRate(){
highTargetHearRate = getMaxHeartRate() * .85;
return highTargetHearRate;
}
public void setHighTargetHearRate(){
this.highTargetHearRate = highTargetHearRate;
}
public static String displayTargetHeartRate(TargetHeartRateCalculator patient){
String hRateRange = String.format("%.2f BPM - %.2f BPM", patient.getLowTargetHearRate(), patient.getHighTargetHeartRate());
return hRateRange;
}
public static String displayMaxHeartRate(TargetHeartRateCalculator patient){
String mHeartRate = String.format("%.2f BPM", patient.getMaxHeartRate());
return mHeartRate;
}
public static String patientInfo(TargetHeartRateCalculator patient) {
String result = String.format("Patient Name: %s %s DOB: %d/%d/%d",
patient.getfName(), patient.getlName(), patient.getBMonth(), patient.getBDay(), patient.getBYear());
return result;
}
}

You should read all variables you need to construct your TargetHeartRateCalculator instance.
System.out.print("Please enter your first name: ");
String firstName = input.next();
System.out.print("Please enter your lastname: ");
String lastName = input.next();
System.out.print("Please enter your birthday day: ");
String birthdayDay = input.nextInt();
System.out.print("Please enter your birthday month: ");
String birthdayMonth = input.nextInt();
System.out.print("Please enter your birthday year: ");
String birthdayYear = input.nextInt();
TargetHeartRateCalculator patient = TargetHeartRateCalculator(firstName, lastName,
birthdayDay, birthdayMonth, birthdayYear);
Then, you can call your static methods after initialized your TargetHeartRateCalculator.
TargetHeartRateCalculator.displayTargetHeartRate(patient);
But, instead of putting everything into a class and using static methods in TargetHeartRateCalculator, you should divide your TargetHeartRateCalculator into two which can be Patient and TargetHeartRateCalculator.
Patient class can be like this:
import java.time.LocalDateTime;
public class Patient {
private String fName;
private String lName;
private int dOB;
private int bMonth;
private int bDay;
private int bYear;
private int ageYears;
private int currentYear = LocalDateTime.now().getYear();
private int currentMonth = LocalDateTime.now().getMonthValue();
private int currentDay = LocalDateTime.now().getDayOfMonth();
public Patient(String fName, String lName, int bMonth, int bDay, int bYear) {
this.fName = fName;
this.lName = lName;
this.bMonth = bMonth;
this.bDay = bDay;
this.bYear = bYear;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public int getbMonth() {
return bMonth;
}
public void setbMonth(int bMonth) {
this.bMonth = bMonth;
}
public int getbDay() {
return bDay;
}
public void setbDay(int bDay) {
this.bDay = bDay;
}
public int getbYear() {
return bYear;
}
public void setbYear(int bYear) {
this.bYear = bYear;
}
public int getAgeYear(){
return currentYear -bYear;
}
public int getAgeMonth(){
return currentMonth - bMonth;
}
public int getAgeDay(){
return currentDay - bDay;
}
}
The calculations will be in another class that take Patient object as an parameter and make calculations.

If I understand correctly, you're trying to get input into the constructor? I'll show one field since the rest are all the same
Scanner input = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fnInput = input.nextLine();
// repeat print and scan, as needed
TargetHeartRateCalculator patient1 = TargetHeartRateCalculator(fnInput); // add more parameters
Then you'll want have instance methods, not static methods with parameters.
public void patientInfo() {
System.out.printf("%s%n", this.getfName()); // for example
}
You call those methods like this
patient1.patientInfo();
And I think you should remove the print statements from the main method

Related

How to fix thid error ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 months ago.
I don't know where the problem is occurring I am trying to print customer details I already tried to change the variables but it didn't work What seems to be the problem? i already tried so many things but still not able to fix the errors.
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
String s1[] = sc.nextLine().split(" ");
String s2[] = sc.nextLine().split(" ");
String s3[] = sc.nextLine().split(" ");
int id = Integer.parseInt(s1[0]);
String name = s1[1];
String area = s2[0];
String city = s2[1];
int day = Integer.parseInt(s3[0]);
int month = Integer.parseInt(s3[1]);
int year = Integer.parseInt(s3[2]);
SimpleDate date = new SimpleDate(day, month, year);
Address add = new Address(area, city);
Customer c = new Customer(id, name, add, date);
System.out.print(c);
}
}
class SimpleDate {
private int day;
private int month;
private int year;
SimpleDate(int day, int month ,int year) {
this.day = day;
this.month = month;
this.year = year;
validateDate(this);
}
//gettens
public int getDay() {
return this.day;
}
public int getMonth() {
return this.month;
}
public int getYear() {
return this.year;
}
//setters
public void setDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public static boolean validateDate(SimpleDate d) {
int day = d.getDay();
int month = d.getMonth();
int year = d.getYear();
if (year < 2000) {
return false;
}
if (month > 12 || month < 1) {
return false;
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day < 1 || day >31)
return false;
break;
case 4:
case 6:
case 9:
case 11:
if (day < 1 || day > 30)
return false;
break;
case 2:
if (day < 1 | day > 28) {
return false;
}
break;
}
return true;
}
#Override
public String toString() {
return (day + "/" + month + "/" + year);
}
}
class Address {
private String area;
private String city;
Address(String area, String city) {
this.area = area;
this.city = city;
}
//getters
public String getArea() {
return area;
}
public String getCity() {
return city;
}
//setters
public void setArea(String area) {
this.area = area;
}
public void setCity(String city) {
this.area = city;
}
#Override
public String toString() {
return (area + ", " + city);
}
}
class Customer {
private int custID;
private String name;
private Address address;
private SimpleDate registrationDate;
Customer(int custID, String name, Address address, SimpleDate registrationDate) {
this.custID = custID;
this.name = name;
this.address = address;
if (!(SimpleDate.validateDate(registrationDate)))
this.registrationDate = null;
else
this.registrationDate = registrationDate;
}
//getters
public Address getAddress() {
return this.address;
}
public SimpleDate getRegistrationDate() {
return this.registrationDate;
}
//setters
public void setAddress(Address address) {
this.address = address;
}
public void setRegistrationDate(SimpleDate registrationDate) {
if (!(SimpleDate.validateDate(registrationDate))) {
this.registrationDate = null;
} else {
this.registrationDate = registrationDate;
}
}
#Override
public String toString() {
String date = "";
if (this.registrationDate == null)
date = "unkown";
else
date = this.registrationDate.toString();
String add = "";
if (this.address == null)
add = "Unkown";
else {
add = this.address.toString();
}
String s = String.format("Id: %d\n" +" Name: %s\n" + "Address : %s\n" + "Registere: %d\n");
return s;
}
}
Please give out more details.
What line causes this issue exactly?
Also you can remove all the code aside from the public static void since its never called
The two places that can be giving out the error are these two:
String name = s1[1];
String city = s2[1];
And the issue is the input you are giving them.
s1[1] and s2[1] points at the second word of the line on your input (arrays start at index 0).
So to solve your error your input would have to look like this:
name name
area
city city
And you are probably just writing the input the wrong way.
Or maybe you meant to write this:
String name = s1[0];
String city = s2[0];
There are many places explaining index out of bounds error before having to post a question on stackoverflow.
Please also check out the link in the comments below your question

Testing (if..Else if...Else) statement (not working)

Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work
//package Driver2;
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
r = this.customerPurchase;
if (r > 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public int getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;
//Constructors
/* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
super();
this.customerPurchase = customerPurchase;
//this.customerDiscount = customerDiscount;
}*/
public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
//super(name, address, number, customerPurchase, customerN, rm);
//this.customerPurchase = customerN;
//this.customerDiscount = pc;
}
public Driver1()
{}
//Accessors
/*
public int getcustomerDiscount()
{
return this.customerDiscount;
}
/*
#Override
public int getcustomerPurchase()
{
return this.customerPurchase;
}
//Mutators
#Override
public void setcustomerPurchase(int c)
{
this.customerPurchase = c;
}*/
/*
public void setcustomerDiscount(int r)
{
this.customerPurchase = r;
if (r >= 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
System.out.println("Percent off: "+customer.getcustomerDiscount());
}
}
The code you have pasted require some changes actually.Assuming you need to return the discount percentage based on the customer input you need to do the following changes.
1) You have a setCustomerDiscount in Person class but the entity you are dealing here is of Customer type so you need to add the setCustomerDiscount in the Customer class instead of Person class.
2) As you want to show the percentage in String(as per your sysout statements/ you can also change to Int as required) you need to change the return type to String instead of Int.
3) Another thing is your order of the if/else if conditions should be in descending order.
Once you fix them, you can get your output as expected.
Below I have made those changes:
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public String getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
public void setcustomerDiscount(int r)
{
String customerDiscount = "";
if (r >= 2000)
{
customerDiscount="10%";
System.out.print("10%");
}
else if (r >= 1500)
{
customerDiscount="7%";
System.out.print("7%");
}
else if (r >= 1000)
{
customerDiscount="6%";
System.out.print("6%");
}
else if (r > 500)
{
customerDiscount="5%";
System.out.print("5%");
}
else
{
System.out.print("");
}
this.customerDiscount = customerDiscount;
}
}
public class TestMain
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
scanner.close();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
customer.setcustomerDiscount(customerPurchase);
System.out.println("Percent off: "+ customer.getcustomerDiscount());
}
}
Hope it helps...
I think it is a logical problem. Simply order the discount formula in reverse.
Catch the big numbers first:
if r >= 2000 print 10%
else if r >= 1500 print 7%
else if r >= 1000 print 6%
else if r >= 500 print 5%
else print nothing
I hope that helps you

Student Tracker Application

I need a little help with my application. I want to make a student tracker application in Java. The application should be able to add new students, years, courses, grades and average for grades. I'm using eclipse mars for it.
Can you please tell me how to make the average for grades, and how to assign new year, courses, and grades for every student, please?
Thank you.
enter code here
public Student(String name, String year, String[] course, int [] grades) {
super();
this.name = name;
this.year = year;
Course = course;
Grades = grades;
}
private String name;
private String year;
private String[] Course;
private int [] Grades;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String [] getCourse() {
return Course;
}
public void setCourse(String[] course) {
Course = course;
}
public int [] getGrades() {
return Grades;
}
public void setGrades(int [] grades) {
Grades = grades;
}
//import (default package).Student;
import java.util.Scanner;
public class MainApplication {
public static void main(String[] args) {
String [] w = {"Mate","Fizica"};
int [] x = {8,9,10};
Student a = new Student("Ene Cristian","Anul 2", w ,x);
String [] y = {"Math", "Info"};
int [] z = {7, 10 ,11};
Student b = new Student("Popscu Ion","Anul 1", w, x);
System.out.println(a.getName());
System.out.println(a.getYear());
System.out.println(b.getName());
System.out.println(b.getYear());
}
}
public class Course {
private String Courses;
}
Extend your Student class with the following method:
public int getAverageGrade(){
int averageGrade = 0;
for(int grade : Grades){
averageGrade = averageGrade + grade;
}
averageGrade = averageGrade/Grades.length;
return averageGrade;
}
Afterwards you can print the average grade using:
System.out.println(a.getAverageGrade());

java.util.Scanner; vs JOptionPane; [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please I would like know How would I implement JOptionPane instead of import java.util.Scanner;
I also have 4 separate classes
If i implement JOptionPane will it clean up the code I would also like to know any changes anyone would make.
Employee.Class
import java.text.NumberFormat;
import java.util.Scanner;
public class Employee {
public static int numEmployees = 0;
protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
private NumberFormat nf = NumberFormat.getCurrencyInstance();
public Benefit benefit;
private static Scanner scan;
public Employee() {
firstName = "";
lastName = "";
gender = 'U';
dependents = 0;
annualSalary = 40000;
benefit = new Benefit();
numEmployees++;
}
public Employee(String first, String last, char gen, int dep, Benefit benefit1) {
this.firstName = first;
this.lastName = last;
this.gender = gen;
this.annualSalary = 40000;
this.dependents = dep;
this.benefit = benefit1;
numEmployees++;
}
public double calculatePay1() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("First Name: ").append(firstName).append("\n");
sb.append("Last Name: ").append(lastName).append("\n");
sb.append("Gender: ").append(gender).append("\n");
sb.append("Dependents: ").append(dependents).append("\n");
sb.append("Annual Salary: ").append(nf.format(getAnnualSalary())).append("\n");
sb.append("Weekly Pay: ").append(nf.format(calculatePay1())).append("\n");
sb.append(benefit.toString());
return sb.toString();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public <Gender> void setGender(char gender) {
this.gender = gender;
}
public <Gender> char getGender() {
return gender;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public void setDependents(String dependents) {
this.dependents = Integer.parseInt(dependents);
}
public int getDependents() {
return dependents;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualSalary(String annualSalary) {
this.annualSalary = Double.parseDouble(annualSalary);
}
public double getAnnualSalary() {
return annualSalary;
}
public double calculatePay() {
return annualSalary / 52;
}
public double getAnnualSalary1() {
return annualSalary;
}
public static void displayDivider(String outputTitle) {
System.out.println(">>>>>>>>>>>>>>> " + outputTitle + " <<<<<<<<<<<<<<<");
}
public static String getInput(String inputType) {
System.out.println("Enter the " + inputType + ": ");
scan = new Scanner(System.in);
String input = scan.next();
return input;
}
public static int getNumEmployees() {
return numEmployees;
}
public static void main(String[] args) {
displayDivider("New Employee Information");
Benefit benefit = new Benefit();
Employee employee = new Employee("George", "Anderson", 'M', 5, benefit);
System.out.println(employee.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Temp Employee Information");
Hourly hourly = new Hourly("Mary", "Nola", 'F', 5, 14, 45, "temp");
System.out.println(hourly.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Full Time Employee Information");
Hourly hourly1 = new Hourly("Mary", "Nola", 'F', 5, 18, 42, "full time");
System.out.println(hourly1.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Part Time Employee Information");
Hourly hourly11 = new Hourly("Mary", "Nola", 'F', 5, 18, 20, "part time");
System.out.println(hourly11.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Revised Employee Information");
Benefit benefit1 = new Benefit("None", 500, 3);
Salaried salaried = new Salaried("Frank", "Lucus", 'M', 5, 150000, benefit1, 3);
System.out.println(salaried.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Employee Information");
Benefit benefit11 = new Benefit("None", 500, 3);
Salaried salaried1 = new Salaried("Frank", "Lucus", 'M', 5, 100000, benefit11, 2);
System.out.println(salaried1.toString());
System.out.println("Total employees: " + getNumEmployees());
}
}
SALARIED.CLASS
import java.util.Random;
import java.util.Scanner;
public class Salaried extends Employee {
private static final int MIN_MANAGEMENT_LEVEL = 0;
private static final int MAX_MANAGEMENT_LEVEL = 3;
private static final int BONUS_PERCENT = 10;
private int managementLevel;
private Scanner in;
public Salaried() {
super();
Random rand = new Random();
managementLevel = rand.nextInt(4) + 1;
if (managementLevel == 0) {
System.out.println("Not Valid");
}
//numEmployees++;
}
private boolean validManagementLevel(int level) {
return (MIN_MANAGEMENT_LEVEL <= level && level <= MAX_MANAGEMENT_LEVEL);
}
public Salaried(String fname, String lname, char gen, int dep,
double sal, Benefit ben, int manLevel)
{
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = sal;
super.benefit = ben;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter
another management level value in range [0,3]: ");
manLevel = new Scanner(System.in).nextInt();
} else {
managementLevel = manLevel;
break;
}
}
//numEmployees++;
}
public Salaried(double sal, int manLevel) {
super.annualSalary = sal;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter another
management level value in range [0,3]: ");
in = new Scanner(System.in);
manLevel = in.nextInt();
} else {
managementLevel = manLevel;
break;
}
}
// numEmployees++;
}
#Override
public double calculatePay() {
double percentage = managementLevel * BONUS_PERCENT;
return (1 + percentage/100.0) * annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Management Level: ").append(managementLevel).append("\n");
return sb.toString();
}
}
Hourly.Class
import java.util.Scanner;
public class Hourly extends Employee {
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;
private double wage;
private double hours;
private String category;
private Scanner in;
private Scanner in2;
private Scanner in3;
private Scanner in4;
public Hourly() {
super();
this.wage = 20;
this.hours= 30;
this.category = "full time";
annualSalary = wage * hours * 52;
}
public Hourly(double wage_, double hours_, String category_) {
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage: ");
in2 = new Scanner(System.in);
wage_ = in2.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours: ");
in = new Scanner(System.in);
hours_ = in.nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
category_ = new Scanner(System.in).next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
public Hourly(String fname, String lname, char gen, int dep, double wage_,double hours_, String category_) {
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = annualSalary;
super.benefit = benefit;
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage : ");
in3 = new Scanner(System.in);
wage_ = in3.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours : ");
hours_ = new Scanner(System.in).nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
in4 = new Scanner(System.in);
category_ = in4.next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
private boolean validHour(double hour) {
return (MIN_HOURS <= hour && hour <= MAX_HOURS);
}
private boolean validWage(double wage) {
return (MIN_WAGE <= wage && wage <= MAX_WAGE);
}
private boolean validCategory(String category) {
String[] categories = {"temp", "part time", "full time"};
for (int i = 0; i < categories.length; i++)
if (category.equalsIgnoreCase(categories[i]))
return true;
return false;
}
public double calculatePay() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Wage: ").append(wage).append("\n");
sb.append("Hours: ").append(hours).append("\n");
sb.append("Category: ").append(category).append("\n");
return sb.toString();
}
}
Benefit.Class
public class Benefit {
private String healthInsurance;
private double lifeInsurance;
private int vacationDays;
public Benefit() {
healthInsurance = "Full";
lifeInsurance = 100;
vacationDays = 5;
}
public Benefit(String health, double life, int vacation) {
setHealthInsurance(health);
setLifeInsurance(life);
setVacation(vacation);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Health Insurance: ").append(healthInsurance).append("\n");
sb.append("Life Insurance: ").append(lifeInsurance).append("\n");
sb.append("Vacation Days: ").append(vacationDays).append("\n");
return sb.toString();
}
public void setHealthInsurance(String healthInsurance) {
this.healthInsurance = healthInsurance;
}
public String getHealthInsurance() {
return healthInsurance;
}
public void setLifeInsurance(double lifeInsurance) {
this.lifeInsurance = lifeInsurance;
}
public double getLifeInsurance() {
return lifeInsurance;
}
public void setVacation(int vacation) {
this.vacationDays = vacation;
}
public int getVacation() {
return vacationDays;
}
public void displayBenefit() {
this.toString();
}
}
Start by taking a look at How to Make Dialogs...
What you basically want is to use JOptionPane.showInputDialog, which can be used to prompt the use for input...
Yes, there are a few flavours, but lets keep it simply and look at JOptionPane.showInputDialog(Object)
The JavaDocs tells us that...
message - the Object to display
Returns:user's input, or null meaning the user canceled the input
So, from that we could use something like...
String value = JOptionPane.showInputDialog("What is your name?");
if (value != null) {
System.out.println("Hello " + value);
} else {
System.out.println("Hello no name");
}
Which displays...
Now, if we take a look at your code, you could replace the use of scan with...
public static String getInput(String inputType) {
String input = JOptionPane.showInputDialog("Enter the " + inputType + ": ");
return input;
}
As an example...
Now, what I might recommend is creating a simple helper method which can be used to prompt the user in a single line of code, for example...
public class InputHelper {
public static String promptUser(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
which might be used something like...
String value = InputHelper.promptUser("Please enter the hours worked");
hours_ = Double.parse(value);
And this is where it get's messy, as you will now need to valid the input of the user.
You could extend the idea of the InputHelper to do automatic conversions and re-prompt the user if the value was invalid...as an idea
It is much easier than you think, if you try. Get used to reading the Java API.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Even has examples.
String input;
JOptionPane jop=new JOptionPane();
input=jop.showInputDialog("Question i want to ask");
System.out.println(input);

Homework Help; Reading from multiple files into Vectors/Arrays

Okay my assignment is to read in from 2 separate files. The first file reads in "HallOfFameMember" and should then be stored in a vector.
The second should read in and then be stored to an array of HallOfFame
The HallOfFameMember object has 10 fields. In order firstName, lastName, deceased, month born, day born, year born, totalEarned, yearsPlayed, yearInducted, hall of fame id
The day/month/year born are all going to a separate class to create a date born. The date born is then set within HallOfFameMember. The Fields for a record will be separated by varying numbers of spaces and/or tabs (whitespaces).
After reading a record from this file, call the 10-arg constructor of HallOfFameMember, using the fields from the record as arguments in the constructor call. Add this new HallOfFameMember object to tempHallOfFameMemberVec.
The HallOfFame object has 5 fields. In order hallOfFameId, city, costToVisit, numberOfVisitorsPerYear, and name.
After reading a record from this file, call the 5-arg constructor of class HallOfFame, using the arguments obtained from the line in the file. Add this new HallOfFame object to tempHallOfFameArr.
This is all to be done from the command line.
I know that my current code will not work, I was just trying to figure out some way to do this. Vectors are completely new to me, along with BufferedReader, and I've been trying to use the examples on javapractice.com as well as a few other sites for reference. I know it will be something small that I am overlooking/missing and Ill have a duh moment when I figure it out.
At any rate my current question is this.
How do I read in from a file that has "any number of white spaces/tabs" as the delimiter. And then parse that into the appropriate fields within the appropriate class?
Giving me the code isn't gonna help, if you could just point me to a website or link that I can read to have my duh moment that would be great.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;
public class HW4 {
/**
* #param args
*/
public static void main(String[] args) {
FileReader inputFileA = new FileReader("");
FileReader inputFileB = new FileReader("");
BufferedReader inputB = new BufferedReader(inputFileB);
Vector<HallOfFameMember> tempHallOfFameMemberVec = new Vector<HallOfFameMember>();
try{
BufferedReader inputA = new BufferedReader(inputFileA);
try {
String line = null;
while ((line = inputA.readLine()) != null){
}
}
}
String newHallOfFameLine = inputB.toString();
String delims = "[ \t]";
HallOfFame[] tempHallOfFameArr = newHallOfFameLine.split(delims);
for (int i = 0; i < args.length; i += 5) {
tempHallOfFameArr[i/5].setHallOfFameId(Integer.parseInt(args[i]));
tempHallOfFameArr[i/5].setCity(args[i+1]);
tempHallOfFameArr[i/5].setCostToVisit(Integer.parseInt(args[i+2]));
tempHallOfFameArr[i/5].setNumberOfVisitorsPerYear(Integer.parseInt(args[i+3]));
tempHallOfFameArr[i/5].setName(args[i+4]);
}
}
class HallOfFameMember {
private String firstName;
private String lastName;
private boolean deceased;
private int dateOfBirth;
private double totalEarned;
private int yearsPlayed;
private int yearInducted;
private int HallOfFameId;
public HallOfFameMember() {
}
public HallOfFameMember(String firstName, String lastName,
boolean deceased, int day, int month, int year, double totalEarned,
int yearsPlayed, int yearInducted, int hallOfFameId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.deceased = deceased;
this.dateOfBirth = month + day + year;
this.totalEarned = totalEarned;
this.yearsPlayed = yearsPlayed;
this.yearInducted = yearInducted;
HallOfFameId = hallOfFameId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isDeceased() {
return deceased;
}
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
public int getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(int dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getTotalEarned() {
return totalEarned;
}
public void setTotalEarned(double totalEarned) {
this.totalEarned = totalEarned;
}
public int getYearsPlayed() {
return yearsPlayed;
}
public void setYearsPlayed(int yearsPlayed) {
this.yearsPlayed = yearsPlayed;
}
public int getYearInducted() {
return yearInducted;
}
public void setYearInducted(int yearInducted) {
this.yearInducted = yearInducted;
}
public int getHallOfFameId() {
return HallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
HallOfFameId = hallOfFameId;
}
public double averageYearlySalary(double averageYearlySalary) {
return averageYearlySalary = (totalEarned / yearsPlayed);
}
}
class Date {
private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
super();
this.month = month;
this.day = day;
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
class HallOfFame {
private int hallOfFameId;// ID of the hall of fame
private String name;// Name of the hall of fame
private String city;// the city in which the hall of fame is located
private double costToVisit;// cost in dollars for a visitor to a hall of
// fame for 1 day
private int numberOfVisitorsPerYear;
private static final double maxCostToVisit = 37.50;
public HallOfFame() {
}
public HallOfFame(int hallOfFameId, String name, String city,
double costToVisit, int numberOfVisitorsPerYear) {
super();
this.hallOfFameId = hallOfFameId;
this.name = name;
this.city = city;
this.costToVisit = costToVisit;
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public int getHallOfFameId() {
return hallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
this.hallOfFameId = hallOfFameId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getCostToVisit() {
if (costToVisit <= maxCostToVisit) {
return costToVisit;
} else
return maxCostToVisit;
}
public void setCostToVisit(double costToVisit) {
this.costToVisit = costToVisit;
}
public int getNumberOfVisitorsPerYear() {
return numberOfVisitorsPerYear;
}
public void setNumberOfVisitorsPerYear(int numberOfVisitorsPerYear) {
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public static double getMaxcosttovisit() {
return maxCostToVisit;
}
public double totalAnnualRevenue(double totalAnnualRevenue) {
totalAnnualRevenue += costToVisit * numberOfVisitorsPerYear;
return totalAnnualRevenue;
}
}
class ReportWriter{
private Vector<HallOfFameMember> hallOfFameMemberVec;
private HallOfFame[] hallOfFameArr;
public ReportWriter() {
}
public Vector<HallOfFameMember> getHallOfFameMemberVec() {
return hallOfFameMemberVec;
}
public void setHallOfFameMemberVec(Vector<HallOfFameMember> hallOfFameMemberVec) {
this.hallOfFameMemberVec = hallOfFameMemberVec;
}
public HallOfFame[] getHallOfFameArr() {
return hallOfFameArr;
}
public void setHallOfFameArr(HallOfFame[] hallOfFameArr) {
this.hallOfFameArr = hallOfFameArr;
}
public void displayReports(){
}
}
A couple tips:
I don't want to do your homework for you, but I can't think of a quick tutorial to point you to that covers exactly what you're doing.
You're on the right track with .split, but your delimiter expression won't work for multiple spaces/tabs. Try this:
String delims = "\\s+";
That will break up your string on any consecutive sequence of one or more whitespace characters.
Also, you need to move the split up into your while loop, as well as the creation of each HallOfFameMember object. In each iteration of the loop you want to:
Split the line that you read from the file to create an array of strings representing the values for one record.
Create a new HallOfFameMember using the values from your string array. (tempHallOfFameArr[0] for first name, tempHallOfFameArr[1] for last name, etc.)
Add the new HallOfFameMember that you created to your vector
If you'd like more detail on any of these steps, I'm happy to elaborate.

Categories