How to call on a field from a new object - java

I created a class called "Person" here it is: (ignore the toString. I haven't done anything with that yet)
public class Person {
public String firstName;
public String middleName;
public String lastName;
public Person() {
firstName = "first";
middleName = "middle";
lastName = "last";
}
public Person(String first, String middle, String last) {
firstName = first;
middleName = middle;
lastName = last;
}
public String toString() {
return (firstName + " " + middleName + " " + lastName);
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
}
And then I created an implementation class in a new file, this is it:
import java.util.*;
public class TestProgPerson
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
String first;
String middle;
String last;
Person name = new Person("Joe", "Smith", "Blow");
System.out.println("Name: " + name);
System.out.println("Please enter a last name, to check if it corresponds with the persons last name: " );
last = console.nextLine();
if (last == (objectReference.lastName))
System.out.println("The last name you entered matches the persons last name");
else
System.out.println("The last name you entered does not match the persons last name");
}
}
So what I want it to do is this: Have an object with the first name, middle name, and last name. Output that name. (The program works this far). Then I want to have the user enter a last name, and the program checks to see if the entered last name is the same as the last name in the object. How do I go about calling just an individual string from that object?

Here you are calling the name object of the class but not any field of that class.
System.out.println("Name: " + name);
You can call fields here by using the object of the class and the dot operator.
For Example.
System.out.println("Name: " + name.firstName + " " + name.middleName + " " + name.lastName);
Moreover because strings are Objects and should be compared with the equals method.

Related

Mooc Helsinki Part 1 Week 4 Exercise 18 Java

The program described here should be implemented in the class PersonalInformationCollection. NB! Do not modify the class PersonalInformation.
After the user has entered the last set of details (they enter an empty first name), exit the repeat statement.
Then print the collected personal information so that each entered object is printed in the following format: first and last names separated by a space (you don't print the identification number). An example of the working program is given below:
Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:
Jean Bartik
Betty Holberton
The PersonalInformation class:
public class PersonalInformation {
private String firstName;
private String lastName;
private String identificationNumber;
public PersonalInformation(String firstName, String lastName, String identificationNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.identificationNumber = identificationNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getIdentificationNumber() {
return identificationNumber;
}
#Override
public String toString() {
return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
}
}
My solution which I can only print all values instead of only Firstnames and the Lastnames from the array:
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
while (true) {
System.out.println("First name: ");
String firstName = scanner.nextLine();
if (firstName.equals("")) {
break;
}
System.out.println("Last name: ");
String lastName = scanner.nextLine();
System.out.println("Identification number: ");
String identificationNumber = scanner.nextLine();
infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));
}
System.out.println(infoCollection);
}
}
I need to modify the code. I am a beginner, an explanatory suggestion would be much appreciated.
Instead of
System.out.println(infoCollection);
you´ll have
infoCollection.stream().forEach(p -> System.out.println(p.getFirstName() + " " + p.getLastName()));
public class Main {
public static void main(String[] args) {
// write your code here
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("First name: ");
String firstName = scanner.nextLine();
if (firstName.equals("")) {
break;
}
System.out.println("Last name: ");
String lastName = scanner.nextLine();
System.out.println("Identification number: ");
String identificationNumber = scanner.nextLine();
infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));
}
for (int i = 0; i < infoCollection.size(); i++) {
System.out.println(infoCollection.get(i).getFirstName() + " "
+ infoCollection.get(i).getLastName());
}
}
}
After the while statement, to print just the first and last names, try:
for (int i = 0; i < infoCollection.size(); i++) {
System.out.println(infoCollection.get(i).getFirstName() + " " + infoCollection.get(i).getLastName());
}
for (PersonalInformation personalInformation: infoCollection) {
System.out.println(personalInformation.getFirstName() + ' ' +
personalInformation.getLastName());
}

Classes and subclass printing

I am trying to print the grade for the student subclass, i feel like i need some type of if statement or array.I am trying to make a code that can be passed a number such as 3 for "Junior" but can also be called through a code such Student.JUNIOR to print the grade level junior. my desired output is:
class Person {
String name;
String campus;
String phone;
String email;
int FRESHMAN = 1;
int SOPHMORE = 2;
int JUNIOR = 3;
int SENIOR = 4;
public Person(String n, String cam, String cell, String mail) {
name = n;
campus = cam;
phone = cell;
email = mail;
}
public String toString() {
return "Name:" + name + "; Campus:" + campus + "; Phone:" + phone + "; Email:" + email + " ";
}
}
class Student extends Person {
int grade;
public Student(String n, String cam, String cell, String mail, int grade) {
super(n, cam, cell, mail);
}
public String toString() {
return super.toString() + "\nClass:";
}
}
class Employee extends Person {
private String title;
public Employee(String n, String cam, String cell, String mail, String position) {
super(n, cam, cell, mail);
title = position;
}
public String toString() {
return super.toString() + "\nTitle:" + title;
}
}
public class Exam3c {
public static void main(String[] args) {
String name = "David";
String campus = "Terry";
String phone = "302-573-3254";
String email = "Genos#edu";
Person P1 = new Person(name, campus, phone, email);
System.out.println("P1: \n" + P1);
Student S1 = new Student(name, campus, phone, email, 1);
System.out.println("S1: \n" + S1);
Student S2 = new Student("Bill While", "Nowhere", "012-345-6789", "bw#nowhere.edu", 3);
System.out.println("S2: \n" + S2);
Employee E1 = new Employee(name, campus, phone, email, "Faculty");
System.out.println("E1: \n" + E1);
}
}
I think you're looking for enums. They have a lot of very useful features; in addition to being nicely type safe in a way that "Magic Ints" are not, you can also fairly fluidly treat them as Strings for debugging.

stack overflow error when using constructor with 2D dynamic graphic [duplicate]

Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)

How do I create a class to sort a file in java

I have my program reading in the file(which contain first name and last names) from the user and printing it out. Now I need to write a method to sort the contents of the file by last name to call in the main. My question is where to begin. I started making my class for sortFile but am stuck on where to even begin.
package javaproject1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class JavaProject1 {
public static void main(String[] args) throws FileNotFoundException
{
String check = "y";
do{
Scanner fileRead = new Scanner(System.in);
System.out.println("Enter the name of the file: ");
File myFile = new File(fileRead.next());
Scanner scanTwo = new Scanner(myFile);
while(scanTwo.hasNext())
{
String i = scanTwo.next();
String j = scanTwo.next();
String sortLast;
System.out.println(i + " " + j + " ");
}
System.out.println();
Scanner anw = new Scanner(System.in);
System.out.println("Add another? y/n ");
check = anw.next();
}while(check.equals("y"));
}
public File sortFile(String sortLast)
{
}
}
Create a class Person implementing the Comparable interface:
public class Person implements Comparable<Person> {
protected String firstName;
protected String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
#Override
public int compareTo(Person o) {
return this.lastName.compareTo(o.lastName);
}
}
The class overrides the compareTo method, defining the sorting.
You can then store the file contents you read, in a SortedSet<Person> like TreeSet.
Assuming i is the first name and j is the last name, add the following two lines to your code:
String check = "y";
SortedSet<Person> persons = new TreeSet<>();
and
System.out.println(i + " " + j + " ");
persons.add(new Person(i, j));
persons will always contain the file contents you read so far, sorted by last name.
After the }while(check.equals("y")); you can then do a:
for (Person person : persons) {
System.out.println(person);
}

odd output when using multiple classes

I am very new with java programming and I am close to finishing a very big project for me. I am trying to make an employee registry that simply relays information back. Whenever I enter the info it just returns stuff like Name#5a965654. My classes are below and any help would be appreciated.
Main:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employees[] = new Employee[employeeCount];
String firstName;
String lastName;
String street;
String city;
String state;
String zipCode;
String monthHired;
String dateHired;
String yearHired;
int employeeID;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the first name of employee " + (x + 1));
firstName = Input.nextLine();
System.out.println("Please enter the last name of employee " + (x + 1));
lastName = Input.nextLine();
System.out.println("Please enter the street of employee " + (x + 1));
street = Input.nextLine();
System.out.println("Please enter the city of employee " + (x + 1));
city = Input.nextLine();
System.out.println("Please enter the state of employee " + (x + 1));
state = Input.nextLine();
System.out.println("Please enter the zip code of employee " + (x + 1));
zipCode = Input.nextLine();
System.out.println("Please enter the month hired for employee " + (x + 1));
monthHired = Input.nextLine();
System.out.println("Please enter the date hired for employee " + (x + 1));
dateHired = Input.nextLine();
System.out.println("Please enter the year hired for employee " + (x + 1));
yearHired = Input.nextLine();
Name name = new Name(firstName, lastName);
name.setName(firstName, lastName);
Address address = new Address(street, city, state, zipCode);
DateOfHire hireDate = new DateOfHire(monthHired, dateHired, yearHired);
employees[x] = new Employee(name, address, hireDate, x);
}
for(int x = 0; x < employeeCount; x++)
{
employees[x].printInfo(x);
}
}
}
Employee class:
public class Employee
{
private Name name;
private Address address;
private DateOfHire hireDate;
int ID;
public Employee()
{
}
public Employee(Name name, Address address, DateOfHire hireDate, int x)
{
this.name = name;
this.address = address;
this.hireDate = hireDate;
this.ID = x;
}
public void printInfo(int x)
{
System.out.println("Employee-" + (x + 1));
System.out.println("Name: " + this.name);
System.out.println("Address: " + this.address);
System.out.println("Date of Hire: " + this.hireDate);
}
}
Format of Name, DateHired, and Address classes:
public class Name
{
private String firstName;
private String lastName;
public Name()
{
}
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
}
A Name is not the same as a String, so when you print this.name in Employee.printInfo, it prints Name#[numbers], indicating that what you're printing is a Name object at the location described by the numbers.
Try replacing that line with
System.out.println("Name: " + this.name.getName());
Also, you'll need to do something similar for the Address and DateOfHire, but I don't know what you have implemented for those, so I can't really say what specifically to do. Essentially, though, you'll need a method that gives a string representation of whatever object it is that you want to print.
All classes in Java extend from the java.lang.Object which has a method toString(). This method is implemented as
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
Whenever you call
System.out.println("Name: " + this.name);
String concatenation is done by implicitly calling the toString() method of your instance. If your class doesn't implement (override) the toString() method, then Object's implementation is used.
See the String Conversion rules in the Java Language Specification.
Otherwise, the conversion is performed as if by an invocation of the
toString method of the referenced object with no arguments; but if the
result of invoking the toString method is null, then the string "null"
is used instead.
Since your Name class does not have a toString() method, then its parent class' method is called, ie. Object#toString() and you get the output you see.
You should override the toString() method in all your classes. For example,
public class Name
{
private String firstName;
private String lastName;
public Name()
{
}
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
return firstName + " " + lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
}
It does not matter than toString() and getName() return the same thing in this case. You have to follow the language spec.
You should implement String toString() method if you wanna print an object

Categories