Using the getName Method - java

Include the following:
A method getFirstName that will return a Student object's first name
A method getLastName that will return a Student object's last name
A statement to print "The student's first name is " with your first name returned from the getFirstName method.
A statement to print "The student's last name is " with your last name returned from the getLastName method.
This is what I have so far:
public class Student
{
//the student's full name
String FirstName;
String LastName;
/**
* Create a new student with a given name a
*/
public Student(String name)
{
FirstName = name;
LastName = name;
}
/**
* Return the first name of this student
*/
public String getFirstName()
{
return FirstName;
}
/**
* Return the last name of this student
*/
public String getLastName()
{
return LastName;
}
public static void main(String[] args)
{
//gives a name to the students
Student FirstName = new Student("Samantha");
Student LastName = new Student("Jones");
//each object calls the getName method
System.out.println("The students first name is: " +Student.getFirstName());
System.out.println("The students last name is: " +Student.getLastName());
}
}

You create a new object but do not use it later.
You should add a second argument to the Student constructor for lastname:
public Student(String firstname, String lastname)
{
FirstName = firstname;
LastName = lastname;
}
And in main, use your student-objects after creation.
public static void main(String[] args)
{
//gives a name to the students
Student stud1 = new Student("Samantha", "Jones");
Student stud2 = new Student("Timo", "Hantee");
//each object calls the getName method
System.out.println("The students first name is: " + stud1.getFirstName());
System.out.println("The students last name is: " + stud2.getLastName());
}

Replace with that:
public Student(String _firstname, String _lastname)//constructor header
{
FirstName = _firstname;//description of constructors
LastName = _lastname;
}

In your Student Class, the FirstName and LastName are two different variable, so you need to assign different values to it in your constructor. So rather creating constructor with one argument, create it with two arguments, one for firstName and other for lastName. Like below:
public Student(String firstName, String lastName)//constructor header
{
this.firstName = firstName;//description of constructors
this.lastName = lastName;
}
public static void main(String[] args)
{
//gives a name to the students
Student student= new Student("Samantha", "Jones");
//each object calls the getName method
System.out.println("The students first name is: " +student.getFirstName());
System.out.println("The students last name is: " +student.getLastName());
}
Here I would like to suggest you one more thing, that is very important for java programmers, follow Java Naming Conventions. The variable name should be start with small letter.

Related

Adding to an ArrayList using a TUI

I'm implementing a class called "BorrowerTUI" to an existing project for an assignment. I've been trying for hours and I just can't work out how to add to my ArrayList using the TUI. The information that needs to be added is in a class called "Borrower". Here is the constructor:
public Borrower(String fName, String lName, String lNumber, int numberOfBooks,
String street, String town, String postcode)
{
firstName = fName;
lastName = lName;
libraryNumber = lNumber;
noOfBooks = numberOfBooks;
address = new Address(street, town, postcode);
}
Previously, I added the object to the ArrayList using a different class called "BorrowerList". Here is the method:
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
That works with no problems. Now what I'm trying to do is use a TUI to add the same information to the same ArrayList. Here is the constructor for "BorrowerTUI" and the options the user will have:
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner (System.in);
borrowerList = new BorrowerList();
Borrower borrower;
}
private void displayMenu()
{
System.out.println("To add a borrower........................[1]");
System.out.println("To get the total number of borrowers.....[2]");
System.out.println("To remove a borrower.....................[3]");
System.out.println("To show all borrowers....................[4]");
System.out.println("To show a single borrower................[5]");
System.out.println("To close Borrowers.......................[0]");
}
private void addBorrower()
{
borrowerList.addBorrower();
}
That doesn't work and I have tried to implement other solutions with no joy. I tried something along the lines of:
private void addBorrower()
{
myScanner = new Scanner(System.in);
String firstName;
String lastName;
borrower = (firstName, lastName);
System.out.println("Enter your first name: ");
myScanner.nextLine() = firstName;
System.out.println("Enter your last name: ");
myScanner.nextLine() = lastName;
borrowerList.add(borrower);
}
That was a bit of guess work as we haven't actually covered this material in class, we're expected to work it out ourselves having briefly touched on TUIs. Hopefully this is enough information, please let me know if you need me to elaborate or provide any additional code.

Using multiple constructors with one object in Java

I have two constructors for Student and am trying to use both of them with one object. But I should be doing it wrong because my output is not what I expect it to be.
Output:
School: null
Grade Level: 0
Intended Major: null
Student's ID number is: 154324
Student's name: Sam Bay
Student's GPA: 3.56
Code for class definition:
public class Student
{
private int id, gradeLevel;
private String name, school, major;
private double gpa;
//constructor to initialize the instance variables of student object
public Student(int id, String name, double gpa)
{
this.id = id;
this.name = name;
this.gpa = gpa;
}
public Student(int gradeLevel, String school, String major)
{
this.gradeLevel = gradeLevel;
this.school = school;
this.major = major;
}
//toString() to display the attributions of the student object
public String toString()
{
return "School: " + school +
"\nGrade Level: " + gradeLevel +
"\nIntended Major: " + major + "\n" +
"\nStudent's ID number is: " + id +
"\nStudent's name: " + name +
"\nStudent's GPA: " + gpa;
}
}//end class
code for main:
public class StudentDrive
{
public static void main(String [] args)
{
//creating student objects
Student sam = new Student(12, "Alpha High School", "Biology");
sam = new Student(154324, "Sam Bay", 3.56);
System.out.println(sam);
}
}
It seems like I've initialized the first part but I get null and 0??!!!
You can't use two constructors simultaneously on a single object.
In your code:
Student sam = new Student(12, "Alpha High School", "Biology");
creates a new Student object and assigns its reference to the variable sam.
On your next line:
sam = new Student(154324, "Sam Bay", 3.56);
This creates another Student object, separate from the first, and reassigns sam to refer to it instead. In the process, you end up orphaning the original Student and leave it open to garbage collection.
What you really want to do is either pass all data required for by a Student through a single constructor, or provide getters/setters (e.g. setGradeLevel(int level)) and a layer of exceptions that prevent methods from accessing a Student object until all fields are filled. The first option is generally more sound.
For example, a complete constructor would look something like this (formatted for readability):
public Student(int id, int gradeLevel, String name,
String school, String major, double gpa)
{
// fill your fields in here
}
I think you should read through the docs for a constructor again ;)
With Student sam = new Student(12, "Oakton High School", "Biology");
you are creating a Student-object with the given parameters and storing it in the variable sam.
When you call sam = new Student(154324, "Sam Bay", 3.56); you are again creating a new Student-object and storing it in sam. You are not modifying the first object but rather discarding it and creating a new one.
You should try adding a method to your Student object like:
public void setAdditionalValues(int id, String name, double gpa){
this.id = id;
this.name = name;
this.gpa = gpa;
}
Hope this is helpful :)
EDIT: as mentioned earlier you could also use one constructor that takes all the arguments or implement setters for each attribute of the Student-object like this:
public void setName(String name){
this.name = name;
}

how do i add or delete something from an array?

I am writing this program that will take in the names, ages and salaries for 5 different people from the user and will put them in an array.
I then want to write a method that will ask the user for another name, age and salary and add that into the array. Also a method that will as for the name of someone who's already in the array and will delete the information of the person with that age from the array.
The first method will increase the array size by 1 and the second will decrease the array size by 1. so far this is what I have:
ArrayList<details> details = new ArrayList<details>();
for(int x = 0; x < 4; x++) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name: ");
String firstName = scan.nextLine();
System.out.println("Enter the last name: ");
String lastName = scan.nextLine();
System.out.println("Enter the age: ");
int age = scan.nextInt();
System.out.println("Enter the salary: ");
double salary = scan.nextDouble();
details.add (new details(firstName, lastName, age, salary));
}
I don't know how to go about doing this. I need some help!
thanks!
You can have a class Person with the class variables you require (name,age,salary)
class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}
Define the getter and setter methods for each of the class variables. For e.g
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
In your main class read the input from STDIN as you are doing it. Instantiate the Person object for each of the 5 person.
Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);
Now, you can add each Person to your list and remove them too.
For removing any Person you would have to search for the Person through the ArrayList by name. That would be iterating over the length of ArrayList and comparing the name of each.
The final class would look like,
public class Solution{
private ArrayList<Person> details = new ArrayList()<Person>;
public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}
Hope this helps.
dud first of all, i can see that u have used arrayList name & Class name both same so please update that.
secondary use Map in place of Class like in if condition
if(){
Map userDetails = new HashMap();
map.put("firstname",firstname);
..
..
map.put("salary",scan.nextDouble());
details.add(map)
}
and on time of delete iterate ArrayList
for(int i=0;i<details.size();i++){
Map tempMap = details.get(i);
if(temp.get("firstname").toString() == "Given Name"){
}else{
// your logic
}
}
Hope will help you please let me know if any doubts.
use this code for removing employee
void removeEmployee(String name){
for(Employee emp :details){
if(name.equals(emp.getName())){
details.remove(emp);
break;
}
}
}
and do include exception handling

How to load an ArrayList with instances of an Object I created

NOTE: I edited my code to how I think people are trying to tell me but it still doesn't give me my desired output. Now my output is "examples.search.Person#55acc1c2" however many times I enter new first and last names. At least it's making it through the code with out crashing lol
I am learning how to use ArrayLists and need to load an Array list with instances of an Object I created. I know how to do this with an array but for this assignment I need to do it with an ArrayList. Here's an example of what I need to do.
// my "main" class
package examples.search;
import java.util.ArrayList;
import dmit104.Util;
public class MyPeople {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
Person tempPerson = new Person();
String firstName;
String lastName;
char choice = 'y';
int count = 1;
// fill my ArrayList
do {
people.add(tempPerson);
// I have a Util class that has a prompt method in it
firstName = Util.prompt("Enter First Name: ");
lastName = Util.prompt("Enter Last Name: ");
tempPerson.setFirstName(firstName);
tempPerson.setLastName(lastName);
count++;
choice = Util.prompt(
"Enter another person? [y or n]: ")
.toLowerCase().charAt(0);
} while (choice == 'y');
// display my list of people
for(int i = 0; i < people.size(); i += 1) {
System.out.print(people.get(i));
}
}
}
// my Person class which I am trying to build from
public class Person {
// instance variables
private String firstName;
private String lastName;
// default constructor
public Person() {
}
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;
}
}
I've tried it a number of ways but no matter what my ArrayList doesn't fill up. Like I mentioned I can do it no problem with an array or even if I had a loaded constructor method but I don't. In my actual assignment I am supposed to do it with the set methods.
I have looked everywhere and cannot find the solution for my problem and being friday my instructor isn't in.
Thank you so much in advance
Leo
You'll have to create a Person and then add it to the ArrayList.
for (int i = 0; i < count; i++) {
Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
people.add(person);
}
Its crashing because your line people.get(i).setFirstName(firstName); is first trying to what is at index i, but you have not set anything yet.
Either first set people[i] to a empty Person, or make a person using firstName and lastName, and add it to people using people.add(person);
You have an ArrayList<Person>, but that alone only defines a list of potential Person instances. But so far, each of the list entries is null. The get(i) returns null, and the following null.setFirstName(..) causes a NullPointerException.
So you need to create the instances of Person that are supposed to go into the list:
firstName = Util.prompt("Enter First Name: ");
Person p = new Person(); //create the instance
people.add(p); //add the instance to the list
p.setFirstName("..."); //set any values
Now you are storing the Person Object into an ArrayList and printing that Object.
To print the firstname and lastName when you print the Person object, you will have to override toString method.
Add the following code in your Person class
public String toString(){
return String.format("[Personn: firstName:%s ,lastName: %s]", firstName,lastName);
}
As for the second question you had, you have to override the toString() method in the Person class. The outputs you are getting, such as examples.search.Person#55acc1c2 is the default toString() method from the Object class, which is defined as class#hashCode

Having trouble storing data in class constructors, learning OOP

Here is the assignment I"m supposed to complete:
Write a program that models an employee. An employee has an employee number, a name, an address, and a hire date. A name consists of a first name and a last name. An address consists of a street, a city, a state (2 characters), and a 5-digit zip code. A date consists of an integer month, day and year.
Use an Employee class, a Name class, an Address class, and a Date class in your solution.
Your program should prompt the user to enter data for several employees and then display that data. The number of employees to store data for shall be entered from the command line.
What I'm confused about is how to use all the different classes for storing info.
Here is my code (sorry this post is so dang long)
import java.util.Scanner;
public class unitTenDemo
{
public static void main ( String [ ] args )
{
Scanner input = new Scanner ( System.in );
System.out.print ( "Enter the number of employees" );
System.out.println ( "\t" );
int employees = input.nextInt ( );
for ( int count = 0; count < employees; count ++ )
{
System.out.print ( "Enter the employees' numbers" );
int employeeNumber = input.nextInt ( );
System.out.println ( );
System.out.println ( "The number is " +employeeNumber );
System.out.println ( );
}
}
}
//that was the actual output code
//here's the constructor that I'm stuck on
public class unitTen
{
int employeeNumber;
public int Employee ( int empNum )
{
employeeNumber = empNum;
}
string employeeName;
public void Name ( string empName )
{
employeeName = empName;
}
string street;
string city;
string state;
int zipCode;
}
Don't put everything into the constructor. It's okay to write a constructor that builds an object that is not fully initialized. You can organize your program as follows:
Find out how many Employee objects there will be (user input)
Create an array of Employee objects of the appropriate length
For each element of the array, assign a new Employee to that element
For each element of the array, prompt the user for each piece of data needed to properly initialize the Employee.
The last step (which deals with only one Employee at a time) will break down into a lot of details, since each Employee object has a lot of information. Just go through all the elements systematically.
This code won't compile at all. Yopu have declaired int as return type and not returning anything from the method.
public int Employee ( int empNum )
{
employeeNumber = empNum;
}
In addition to the answer pointed to by #Ted , you should modify your Employee class accordingly and then invoke the constructors as you please.
public class Employee // you should change the name of class to Employee
{
int employeeNumber;
public Employee(){}; // default constructor to create empty Employee objects
public Employee ( int empNum ) // constructor cannot have any return type
{
employeeNumber = empNum;
}
string employeeName;
public Employee( string empName, int empNum ) // you can create multiple constructors with different parameters.
{
employeeName = empName;
employeeNumber = empNum;
}
string street;
string city;
string state;
int zipCode;
// you can create getters and setters for these fields
}

Categories