I'm currently learning java and starting on methods, classes and objects. I'm attempting to code a simple program to have set values for 2 separate employee's at a company that would then allow for user input to alter certain variables of a specific object. The variables needing to be updated via user input will be the MonthlySalary and FirstName of the object employee2. I'm not really sure how to structure the user input part and I'm at a loss trying to find a solution.
import java.util.Scanner;
public class EmployeeTest
{
public static void main( String[] args ){
Scanner input = new Scanner(System.in);
// Create 2 Employee objects
Employee employee1 = new Employee( "Jane", "Doe", 5000 );
Employee employee2 = new Employee( "John", "Bloggs", 4500 );
// Do other steps (not requiring input)
// Ask for user input of Employee 2's new first name
System.out.println( "Please enter new first name for Employee 2: \n");
String input = employee2.newFirstName();
// repeat above to set Employee 2's new salary then display new information
}
}
With the Class file Employee.java
public class Employee
{
private String firstName; // Employee's First Name
private String lastName; // Employee's Last Name
private double monthlySalary; // Employee's Monthly Salary
// Employee constructor
public Employee( String initFirstName, String initLastName, double initMonthlySalary )
{
firstName = initFirstName;
lastName = initLastName;
if (initMonthlySalary > 0)
monthlySalary = initMonthlySalary;
else
monthlySalary = 0;
}
public Employee( )
{
firstName = "";
lastName = "";
monthlySalary = 0;
}
// Method to assign the employee's First Name
public void setFirstName( String newFirstName )
{
firstName = newFirstName;
}
// Method to assign the employee's Monthly Salary
public void setMonthlySalary( double newMonthlySalary )
{
if (newMonthlySalary > 0) monthlySalary = newMonthlySalary;
}
// Other required methods
}
You are struggling to take input from the console.
System.out.println("Please enter new first name for Employee 2: ");
String firstName = input.next();
employee2.setFirstName(firstName);
System.out.println("Please enter new Salary for Employee 2: ");
double salary = input.nextDouble();
employee2.setMonthlySalary(salary);
This will work for you. And please go through the basic syntaxes first. Because otherwise you are wasting your own time banging your head for this kind of syntactical doubts.
Related
I have a class that has private variables such as employeeName and employeeNumber and methods to set and get employeeName and employeeNumber. This class is called "EmployeesInformation". In this class I have two constructors. One that gets employee's information such as EmployeesInformation(String name, String phoneNumber){...} and another one that gets the same information but also receives two additional bits of information such as String datefired and String reasonForLeave.
Now in another class called "MenuOptionMethods" I have the addEmployee method and fireEmployee method and another method to show employees information.
I created two arrayList in this class called employee and formerEmployee.
Whenever the user adds an employee I put that employee object in the arrayList called employee. When the user fires or removes an employee I want to take all of that employee's information, remove it from arrayList employee and add it to arrayList formerEmployee. That is where I'm having problems. Can someone take a look at my code and tell me what's wrong with it?
public class menuOptionMethods {
Scanner sc = new Scanner(System.in);
private ArrayList<EmployeesInformation> employee;
private ArrayList<EmployeesInformation> formerEmployee;
public menuOptionMethods() {
employee = new ArrayList<EmployeesInformation>();
formerEmployee = new ArrayList<EmployeesInformation>();
}
public void addEmployee(String eName) {
String n = eName;
System.out.println(" Enter date hired: ");
String h = sc.next();
System.out.println(" Enter employee's duty: ");
String d = sc.next();
System.out.println(" Enter employee's phone number: ");
String pN = sc.next();
System.out.println(" Enter employee's pay per hour: ");
double pPH = sc.nextInt();
System.out
.println(" Enter any additional information about employee: ");
String l = sc.next();
EmployeesInformation e = new EmployeesInformation(n, h, d, l, pN, pPH);
employee.add(e);
}
public void fireEmployee(String eName) {
// System.out.println("Enter employee's name: ");
// String name = eName;
System.out.println("Reason for employee's leave?: ");
String reason = sc.next();
System.out.println("Enter date: ");
String dF = sc.next();
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
n = eName;
h = employee.get(i).getDateHired();
d = employee.get(i).getEmployeDuty();
pH = employee.get(i).getPhoneNumber();
pPH = employee.get(i).getEmployePay();
l = employee.get(i).getAdditionalInformation();
employee.remove(i);
}
}
EmployeesInformation fE = new EmployeesInformation(n,h,d,l,pH,pPH,reason,dF); // ERROR HAPPENS HERE
}
}
You can't remove element from list while iterating it with for loop (it will throw ConcurrentModificationException. To do that, you need to use iterator and call remove() method, e.g.:
for(Iterator<Employee> iterator = employees.iterator() ; iterator.hasNext();){
Employee current = iterator.next();
if(current.getName().equals(name)){
iterator.remove();
//Add into former employees' list
break;
}
}
This will remove from existing list.
In your for loop, you don't want to do any removing because the size of the arraylist will change, and that just creates whack that is throwing you off. Assuming every employee has a unique name, you could do something like this (note I simplified making all those new variable by just transferring that employee object from one arraylist to the other):
int index;
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
formerEmployee.add(employee[i]); //date fired and reason fired can be added later
index = i;
break;
}
}
employee.remove(i);
}
I want to know how I can loop a new object within the same class, so that I can repeat the code to have several different objects with different details entered via the Scanner class.
It will probably make sense if I show what I am trying to do:
public class Students
{
private String studFirstName; // Student's first name
private String studSurname; // Student's surname
private String courseName; // Course name
public Students(String sFirstName, String sSurname, String cName)
{
studFirstName = sFirstName;
studSurname = sSurname;
courseName = cName;
}
public String getStudFirstName() // Getter for student's first name
{
System.out.println("Enter in student's first name: "); // Prompts end user for input
Scanner In = new Scanner(System.in); // Creating a new object
studFirstName = In.next(); // Accepts a one word input only
return studFirstName;
}
public String setStudFirstName(String sFirstName) // Setter for student's first name
{
return studFirstName;
}
public static void main (String [] args)
{
Students first[] = new Students[5];
for(Students a : first)
{
}
Students first[] = new Students("", "", "");
String studFirstName = first.getStudFirstName();
}
}
You need a regular for loop in order to assign values within the array.
int numStudents = 5;
Student students[] = new Student[numStudents]; // creates an array of 5 nulls
Scanner scan = new Scanner(System.in);
for(int i = 0; i < numStudents; i++) {
System.out.println("Enter your first name: "); // Prompt
String fname = scan.nextLine(); // Read
Student s = new Student(fname); // Assign
first[i] = s; // Store
}
You really don't need the get methods since you have access to set the values in the constuctor.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Student[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(studFirstName);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
}
}
First, you should take a look at encapsulation. A getter is not meant to take user input. Getter should return the value of a private field. Setters should set the value of a private field.
// This is a field
private String myField;
// This will return the current value for the field 'myField'
public String getMyField() {
return this.myField;
}
// This will asign a new value to the field 'myField'
public void setMyField(String myField) {
this.myField = myField;
}
Answer
You will need a regular for loop to create as many students a you want. I renamed your class 'Students' to Student to fit javas naming conventions.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Stundent[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(name, .....);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
I'm doing an assignment for class which requires me to create an array and add to it as the user wishes. Here's what I have so far:
public void add(Scanner stdIn)
{
entries = new String[1];
Contact add = new Contact(); // Instantiate new Contact instance
String name;
System.out.print("Enter the contact's name: ");
name = stdIn.next();
add.setName(name); // set name in Contact class
String address;
System.out.print("Enter the contact's address: ");
address = stdIn.next();
add.setAddress(address); // set address in Contact class
String phone;
System.out.print("Enter the contact's phone number: ");
phone = stdIn.next();
add.setPhone(phone); // set phone number in Contact class
String email;
System.out.print("Enter the contact's email address: ");
email = stdIn.next();
add.setEmail(email); // set email address in Contact class
final int N = entries.length;
entries = Arrays.copyOf(entries, N + 1);
entries[0] = add.toString();
System.out.print(Arrays.toString(entries));
} // end add
I am not too familiar with using arrays, so trying to copy the old array and create a new array with the old information, as well as add new information is alluding me. The toString method looks like this:
#Override // Overrides method from java.lang.Object
public String toString() // Displays the info for a contact in order
{
return getName() + "\t" + getAddress() + "\t" + getPhone() +
"\t" + getEmail();
}
If you need any more clarification, let me know! Thanks for the help!
As I mentioned in your comment, you need to define the array (could use an ArrayList instead) outside of the method or it will go out of scope and the data will be lost between calls to the add method.
Here is sample code showing how to make multiple calls to add(), each time expanding the array by 1 and printing the result:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayCopy {
String[] entries = new String[0];
public void add(Scanner stdIn)
{
entries = Arrays.copyOf(entries, entries.length + 1);
Contact add = new Contact(); // Instantiate new Contact instance
String name;
System.out.print("Enter the contact's name: ");
name = stdIn.next();
add.setName(name); // set name in Contact class
String address;
System.out.print("Enter the contact's address: ");
address = stdIn.next();
add.setAddress(address); // set address in Contact class
String phone;
System.out.print("Enter the contact's phone number: ");
phone = stdIn.next();
add.setPhone(phone); // set phone number in Contact class
String email;
System.out.print("Enter the contact's email address: ");
email = stdIn.next();
add.setEmail(email); // set email address in Contact class
entries[entries.length-1] = add.toString();
System.out.println(Arrays.toString(entries));
} // end add
public static void main(String[] args) {
ArrayCopy program = new ArrayCopy();
Scanner scan = new Scanner(System.in);
String op = "";
System.out.println("Press A to add a user or E to exit.");
while(!(op = scan.nextLine()).equalsIgnoreCase("E")){
switch(op){
case "A":
program.add(scan);
break;
case "E":
System.out.println("Good Bye.");
System.exit(0);
}
}
}
}
This question already has answers here:
Java: .nextLine() and .nextDouble() differences
(2 answers)
Closed 8 years ago.
I am a beginner of Java. I am trying to create two Scanner objects from a class (which I have created by myself and there i also have created a constructor). I have initialized these two objects by the constructor call and later I want to update these two objects's information by obtaining data from user by Scanner class. When I am creating object by obtaining data from user by using Scanner object, I can create only one object and and the code for the second object are executing thoroughly without obtaining any data from the user. Thus I can create only one object and the code for second object is just displaying in the executing windows without obtaining any data.
Is it that I can't update the data of two objects by Scanner when they are already initialized by constructor call?
Here is the class code from where I want to create two object:
public class Employee {
//instance variables
String firstName;
String lastName;
double salary;
//constructor for three arguments
public Employee(String first_name, String last_name, double month_salary)
{
firstName = first_name;
lastName = last_name;
if(month_salary > 0) //make sure that the salary is not smaller than zero
{
salary = month_salary;
}
}//end of constructor
//set the value of the instance variables
//set first name
public void setFirstName(String first_name)
{
firstName = first_name;
}
//get first name
public String getFirstName()
{
return firstName;
}
//set last name
public void setLastName(String last_name)
{
lastName = last_name;
}
//get last name
public String getLastName()
{
return lastName;
}
//set salary
public void setSalary(double month_salary)
{
if(month_salary > 0) //make sure that the salary is not smaller than zero
{
salary = month_salary;
}
else salary = 0.00;
}
//get salary
public double getSalary()
{
return salary;
}
}
And here are the object's code
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee("M", "R", 5000);
Employee employee2 = new Employee("T", "M", 6000);
System.out.println("Display the intial Employee's information\n");
//showing the Employee2's information
System.out.println("Displaying Employee1's information");
System.out.printf("First Name: %s\nLast Name: %s\nSalary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(), employee1.getSalary());
System.out.println();
//showing the Employee2's information
System.out.println("Displaying Employee2's information");
System.out.printf("First Name: %s\nLast Name: %s\nSalary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(), employee2.getSalary());
System.out.println();
//create an scanner object to get information from user
Scanner input = new Scanner(System.in);
//obtain employee's first name from user
System.out.print("Please enter the first name of employee1: ");
String fName1 = input.nextLine();
//set the first of employee1
employee1.setFirstName(fName1);
//obtain employee's last name from user
System.out.print("Please enter the last name of employee1: ");
String lName1 = input.nextLine();
//set the last of employee1
employee1.setLastName(lName1);
//set the salary employee1's
System.out.print("Please enter employee's salary: ");
double empl_salary1 = input.nextDouble();
//obtain the employe1's salary
employee1.setSalary(empl_salary1);
//display the updated employee1's information
System.out.println("Updated information of employee's information");
System.out.printf("First name :%s\nLast name: %s\nSalary: %.2f\n",
employee1.getFirstName(),employee1.getLastName(), employee1.getSalary());
//obtain employee2's first name from user
System.out.print("Please enter employee2'first name: ");
String fName2 = input.nextLine();
//set the first name of employee2
employee2.setFirstName(fName2);
//obtain employee's last name from user
System.out.print("Please enter the employee2's last name: ");
String lName2 = input.nextLine();
//set the last name of employee2
employee2.setLastName(lName2);
//obtain the salary employee2's
System.out.print("Please enter employee2's salary: ");
double empl_salary2 = input.nextDouble();
//set the employe1's salary
employee2.setSalary(empl_salary2);
}
}
I don't know where is the problem?
Thanks for your time and assistance!
Add input.nextLine(); just before obtaining data for second employee:
input.nextLine();
//obtain employee2's first name from user
System.out.print("Please enter employee2'first name: ");
String fName2 = input.nextLine();
It is because input.nextDouble(); "consumes" only double value, leaving the newline character you entered "unconsumed".
I have following classes in the project:
Account
Customer
Name: fName and lName (both are String fields)
Date: year, month, day (all are int fields)
Bank: contains collection of accounts
InputReader: reads the input from the keyboard
An Account object requires a Customer object and an opening balance.
A Customer object requires a Name object and a Date object.
A Name object requires Strings for first and last names
I need to ask the user for the details to create the Name and Date objects, and also the opening balance.
I have to create a new Account by getting the relevant information from the user, i.e. it asks the user to type in the customer's name, date of birth etc. It reads in the user responses, creates the account and adds it to the bank.
I keep getting an error message saying "java.lang.NullPointerException" when I run the public void createNewAccount() method. Would appreciate any help. Thanks in advance.
Below is my source code for the Bank class.
import java.util.ArrayList;
public class Bank
{
public static final double INTEREST_RATE = 0.012;//1.2%
// instance variables - replace the example below with your own
private ArrayList<Account> accounts;
private InputReader reader;
private Name fullName;
private Date dateOfBirth;
/**
* Constructor for objects of class Bank
*/
public Bank()
{
// initialise instance variables
}
/*
* Adds an existing Account to the bank
* #param account
*/
public void addAccount(Account account)
{
accounts.add(account);
}
public void createNewAccount() {
System.out.println("Please enter your first name: ");
String firstName = reader.readString();
System.out.println("Hello " + firstName + ". " + "What is your last name?");
String lastName = reader.readString();
System.out.println("Your last name is " + lastName);
System.out.println("Please enter your year of birth: ");
int thisYear = reader.readInt();
System.out.println("Please enter your month of birth: ");
int thisMonth = reader.readInt();
System.out.println("Please enter your date of birth: ");
int thisDay = reader.readInt();
Name theName = new Name(firstName, lastName);
Date theDateOfBirth = new Date(thisYear, thisMonth, thisDay);
}
}
You have to initialize reader before you can attempt to read from it.
You can change reader with Scanner. Something like that.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first name: ");
String firstName = scan.next();
System.out.println("Hello " + firstName + ". " + "What is your last name?");
String lastName = scan.next();
System.out.println("Your last name is " + lastName);
System.out.println("Please enter your year of birth: ");
int thisYear = scan.nextInt();
System.out.println("Please enter your month of birth: ");
int thisMonth = scan.nextInt();
System.out.println("Please enter your date of birth: ");
int thisDay = scan.nextInt();
//Then do what you are supposed to do......
Scanner scanner = new Scanner(System.in);
The scanner object has a lot of functions you can use;
Your InputReader reader is declared, but not initialised, hence NullPointerExceptin. Change it to more commonly used:
Scanner scanner = new Scanner(System.in);
Then you can use it's methods for user input:
scanner.nextLine() for strings
scanner.nextInt() for ints
scanner.nextDouble() for doubles
etc.
Check the docs here.
You need to initialize your instance variables:
public class Bank
{
public static final double INTEREST_RATE = 0.012;
private ArrayList<Account> accounts;
private InputReader reader;
private Name fullName;
private Date dateOfBirth;
public Bank()
{
// initialise instance variables <- where it says to
accounts = new ArrayList<Account>();
reader = new InputReader();
...
}
InputReader must be part of the assignment package so I don't know what its constructor properly is.