Issue with getname() and addmemberlist() - java

For some reason my getName() method and and addMemberList() is not working.
I have tried everything parsing and debugging with a friend but nothing seems to work.
main
public static void main(String[] args) throws FileNotFoundException {
initialUserGuide();
Scanner sc = new Scanner(new File("familytree.txt"));
Family fr = new Family(sc);
fr.displayAllMembersList();
processUserInput(fr);
}
static void initialUserGuide(){
System.out.println("The input file consists of names of all Humans");
System.out.println("Enter the Human name from below list, to display his/her maternal line, Paternal line and children");
}
static void processUserInput(Family fr)
{
Scanner input = new Scanner(System.in);
Person person;
System.out.println("newt Human ( enter told " + "quit)?");
String nextLine = input.nextLine();
while(nextLine.length() > 0){
person = fr.find(nextLine);
if(person == null)
System.out.println("NoMatch Occured");
else
{
displayMaternalLine(person);
displayPaternalLine(person);
displayChildren(person);
}
System.out.println("");
System.out.println("next Human (enter to quit)?");
nextLine = input.nextLine();
}
}
static void displayMaternalLine(Person mother)
{
System.out.println("Maternal Line");
int i = 0;
int count = 1;
while(mother != null)
{
for(i = 0;i < count; i++){
System.out.println("");
}
System.out.println(mother.getName());
mother = mother.getMother();
count++;
}
}
static void displayPaternalLine(Person father)
{
System.out.println("Paternal Line");
int i = 0;
int count = 1;
while(father != null)
{
for(i = 0;i < count; i++){
System.out.println("");
}
System.out.println(father.getName());
father = father.getMother();
count++;
}
}
static void displayChildren(Person person)
{
System.out.println("Children");
ArrayList ptr = person.getChildren();
if(ptr.size()==0)
{
System.out.println(" none");
}
for(int i = 0; i < ptr.size(); i++)
{
System.out.println("\t" + ptr.get(i).getName());
}
}
}
Family class
package assignment7;
import java.util.ArrayList;
import java.util.Scanner;
public class Family{
private ArrayList allMembersList;
public Family(Scanner sc){
allMembersList = new ArrayList();
addAllMembersList(sc);
makeParentChildRelation(sc);
}
Person find(String name)
{
for(int i = 0; i < allMembersList.size();i++)
{
if(allMembersList.get(i).getName().equalsIgnoreCase(name))
return (Person) allMembersList.get(i);
}
return null;
}
public void addAllMembersList(Scanner sc){
String line = sc.nextLine();
while(line.length() != 0)
{
Person person = new Person(line);
addMembersList.add(person);
line = sc.nextLine();
}
}
public void makeParentChildRelation(Scanner sc)
{
String nextLine;
String name,motherName,fatherName;
while(sc.hasNextLine())
{
name = sc.nextLine();
motherName = sc.nextLine();
fatherName = sc.nextLine();
Person personn = find(name);
if(!motherName.equals("unknown"))
{
Person mother = find(motherName);
personn.setMother(mother);
mother.addChildren(personn);
}
if(!fatherName.equals("unknown"))
{
Person father = find(fatherName);
personn.setFather(father);
father.addChildren(personn);
}
}
}
public void displayAllMembersList()
{
for(int i = 0; i < allMembersList.size(); i++)
{
Person person = (Person) allMembersList.get(i);
System.out.println(person.getName());
}
}
}
Person class
package assignment7;
import java.util.ArrayList;
public class Person {
private String name;
private Person mother;
private Person father;
private ArrayList children;
public Person(String name)
{
this.name = name;
children = new ArrayList();
}
public void setName(String name)
{
this.name = name;
}
public void setFather(Person Father){
this.father = Father;
}
public void setMother(Person Mother){
this.mother = Mother;
}
public void addChildren(Person Child)
{
children.add(Child);
}
public String getName()
{
return this.name;
}
public Person getFather()
{
return this.father;
}
public Person getMother()
{
return this.mother;
}
public ArrayList getChildren(){
return this.children;
}
}
familytree.txt
Maternal line:
Henry VIIII
Elizabeth of York
Paternal line:
Henry VIII
Henry VII
Children:
Mary I
Elizabeth I
Edward VI
Any help would be greatly appreciated here is the original problem.
Write a family database program. Create a class to represent a person and to store references to the person's mother, father, and any children the person has. Read a file of names to initialize the name and parent-child relationships of each Person. Store the overall list of Persons as an Arraylist. Write an overall main user interface that asks for a name and prints the maternal and paternal family line for that person.

The issue is you are using generic ArrayList to store List of Person objects. You should use List<Person>.
Also, addMembersList should be allMembersList (must be a typo).
Here is working code.
//main
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
initialUserGuide();
Scanner sc = new Scanner(new File("familytree.txt"));
Family fr = new Family(sc);
fr.displayAllMembersList();
processUserInput(fr);
}
static void initialUserGuide() {
System.out.println("The input file consists of names of all Humans");
System.out.println("Enter the Human name from below list, to display his/her maternal line, Paternal line and children");
}
static void processUserInput(Family fr) {
Scanner input = new Scanner(System.in);
Person person;
System.out.println("newt Human ( enter told " + "quit)?");
String nextLine = input.nextLine();
while (nextLine.length() > 0) {
person = fr.find(nextLine);
if (person == null)
System.out.println("NoMatch Occured");
else {
displayMaternalLine(person);
displayPaternalLine(person);
displayChildren(person);
}
System.out.println("");
System.out.println("next Human (enter to quit)?");
nextLine = input.nextLine();
}
}
static void displayMaternalLine(Person mother) {
System.out.println("Maternal Line");
int i = 0;
int count = 1;
while (mother != null) {
for (i = 0; i < count; i++) {
System.out.println("");
}
System.out.println(mother.getName());
mother = mother.getMother();
count++;
}
}
static void displayPaternalLine(Person father) {
System.out.println("Paternal Line");
int i = 0;
int count = 1;
while (father != null) {
for (i = 0; i < count; i++) {
System.out.println("");
}
System.out.println(father.getName());
father = father.getMother();
count++;
}
}
static void displayChildren(Person person) {
System.out.println("Children");
List<Person> ptr = person.getChildren();
if (ptr.size() == 0) {
System.out.println(" none");
}
for (int i = 0; i < ptr.size(); i++) {
System.out.println("\t" + ptr.get(i).getName());
}
}
}
//Family
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Family {
private List<Person> allMembersList;
public Family(Scanner sc) {
allMembersList = new ArrayList<>();
addAllMembersList(sc);
makeParentChildRelation(sc);
}
Person find(String name) {
for (int i = 0; i < allMembersList.size(); i++) {
if (allMembersList.get(i).getName().equalsIgnoreCase(name))
return (Person) allMembersList.get(i);
}
return null;
}
public void addAllMembersList(Scanner sc) {
String line = sc.nextLine();
while (line.length() != 0) {
Person person = new Person(line);
allMembersList.add(person);
line = sc.nextLine();
}
}
public void makeParentChildRelation(Scanner sc) {
String nextLine;
String name, motherName, fatherName;
while (sc.hasNextLine()) {
name = sc.nextLine();
motherName = sc.nextLine();
fatherName = sc.nextLine();
Person personn = find(name);
if (!motherName.equals("unknown")) {
Person mother = find(motherName);
personn.setMother(mother);
mother.addChildren(personn);
}
if (!fatherName.equals("unknown")) {
Person father = find(fatherName);
personn.setFather(father);
father.addChildren(personn);
}
}
}
public void displayAllMembersList() {
for (int i = 0; i < allMembersList.size(); i++) {
Person person = (Person) allMembersList.get(i);
System.out.println(person.getName());
}
}
}
//Person
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private Person mother;
private Person father;
private List<Person> children;
public Person(String name) {
this.name = name;
children = new ArrayList<>();
}
public void setName(String name) {
this.name = name;
}
public void setFather(Person Father) {
this.father = Father;
}
public void setMother(Person Mother) {
this.mother = Mother;
}
public void addChildren(Person Child) {
children.add(Child);
}
public String getName() {
return this.name;
}
public Person getFather() {
return this.father;
}
public Person getMother() {
return this.mother;
}
public List<Person> getChildren() {
return this.children;
}
}

Related

how to get input for an array of class in java?

I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}

Why is there multiple output when I call from an arraylist?

import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}

Java - Returning an "address" from an ArrayList of names and addresses

I've been working on this AP Problem all day with no luck. If anyone can help, it would be appreciated.
I have an ArrayList of Strings composed of names and addresses. After the addresses, there is an empty String and the next name starts. The method getAddress takes a String parameter (a name) and returns the address of the pereson (the lines after the name including the empty String, but stopping there). I'm having trouble writing this method.
import java.util.ArrayList;
public class Recipients {
ArrayList<String> lines = new ArrayList<String>();
public String extractCity(String cityZip) {
int pos = cityZip.indexOf(",");
return cityZip.substring(0, pos);
}
public void printNames() {
System.out.println(lines.get(0));
for (int i = 0; i < lines.size()-1; i++)
if (lines.get(i).substring(0, lines.get(i).length()).equals(""))
System.out.println(lines.get(i+1));
}
public String getAddress(String name) {
String address = "";
int ct = 0;
int place = 0;
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).substring(0, lines.get(i).length()).equals(name)) {
place = i;
for (int j = i+1; j < lines.size(); j++) {
ct = j;
if (!lines.get(i).substring(0, lines.get(i).length()).equals("")) {
ct++;
}
}
for (int k = place; k < ct; k++) {
address = address + lines.get(i);
}
}
}
return address;
}
public void main() {
lines.add("Mr. J Adams");
lines.add("Rose St.");
lines.add("Ithaca, NY 14850");
lines.add("");
lines.add("Jack S. Smith");
lines.add("12 Posy Way");
lines.add("Suite #201");
lines.add("Glendale, CA 91203");
lines.add("");
lines.add("Ms. M.K. Delgado");
lines.add("2 River Dr.");
lines.add("");
System.out.println(getAddress("Jack S. Smith"));
System.out.println("test line break");
}
}
Thank you for your time.
EDIT: This method is supposed to be written in the Recipients class. It has an assumed constructor and I've written other methods inside the class. I've edited the class. I'm having trouble with the logic.
Worksheet says: Write the getAddress method of the Recipients class. This method should return a string that contains only the address of the corresponding name parameter. For example, if name is "Jack S. Smith", a string containing the three subsequent lines of his address should be returned. This string should contain line breaks in appropriate places, including after the last line of the address.
public String getAddress(String name)
You should create class for saving name and address. Please find below mentioned approach.
package hello;
import java.util.ArrayList;
import java.util.List;
class Employee {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class So3 {
public static void main(String[] args) {
List<String> lines = new ArrayList<String>();
lines.add("Mr. J Adams");
lines.add("Rose St.");
lines.add("Ithaca, NY 14850");
lines.add("");
lines.add("Jack S. Smith");
lines.add("12 Posy Way");
lines.add("Suite #201");
lines.add("Glendale, CA 91203");
lines.add("");
lines.add("Ms. M.K. Delgado");
lines.add("2 River Dr.");
lines.add("");
List<Employee> employees = new ArrayList<Employee>();
Employee employee = new Employee();
for (String str : lines) {
if (str.isEmpty()) {
if (employee.getName() != null && employee.getAddress() != null) {
employees.add(employee);
employee = new Employee();
}
} else if (employee.getName() == null) {
employee.setName(str);
} else {
if (employee.getAddress() == null) {
employee.setAddress(str);
} else {
employee.setAddress(employee.getAddress() + " " + str);
}
}
}
if (employee.getName() != null && employee.getAddress() != null) {
employees.add(employee);
}
System.out.println(getAddress(employees, "Ms. M.K. Delgado"));
}
private static String getAddress(List<Employee> employees, String name) {
if (employees != null && name != null) {
for (Employee employee : employees) {
if (name.equals(employee.getName())) {
return employee.getAddress();
}
}
}
return null;
}
}
If you have to use as you have wanted then you need to modify your getAddress method. Try the following getAddress method in your code:
public String getAddress(String name) {
String address = "";
boolean nameFound=false;
for(String str:lines)
{
if(!nameFound && str.equals(name))
nameFound=true;
else if(nameFound && str.isEmpty())
break;
else if(nameFound && !str.isEmpty())
address+=str;
}
return address;
}
You should use HashMap rather than an ArrayList for this. This is a perfect scenario to use HashMap instead.
public class APProblem {
Map<String, List<String>> lines2 = new HashMap<>();
public List<String> getAddress(String name) {
return lines2.get(name);
}
public void main() {
String name = "Mr. J Adams";
List<String> address = Arrays.asList("Rose St.", "Ithaca, NY 14850");
lines2.put(name, address);
name = "Jack S. Smith";
address = Arrays.asList("12 Posy Way", "Suite #201", "Glendale, CA 91203");
lines2.put(name, address);
System.out.println(getAddress("Jack S. Smith"));
System.out.println("Testing line break.");
}
}

input from Keyboard into Array list of persons

I want to accept input from user to populate an Array list of Person. for some reason. I can't get it to work. I can add an item into the list I have created below are my code for reference. in the SimplepersonDatabase class in switch function case 2:, I want to accept an an input of names, date of birth from the user and the program should automatically assign the position number starting from
e.g
001. Damien Kluk September, 12.09.1975
002. James Hunt January , 12.09.2000
I should be able to also delete a person and sort the list of Persons. here are what I have implemented so far.
public class Person { //Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
class List {//List.java
int MAX_LIST = 20;
Person[] persons;
int count;
public List() {
persons = new Person[MAX_LIST];
count=0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
}
public class SimplePersonDataBase { //SimplePersonDataBase.java
private static List list;
private static int nextPersonId;
public static void main(String[] args) {
go();
}
public static void go() {
List link = new List();
TextIO.put("Welcome to the SimplePersonDatabase.\n");
TextIO.putln();
int option;
do{
TextIO.put("available options:\n1) list\n2) add\n3) remove\n4) sort\n5) find\n6) settings\n0) quit\nyour choice:");
option = TextIO.getInt();
switch(option){
case 1:
PersonFunctions.display();
break;
case 2: // Should accept inputs from a user and update the Persons database
TextIO.put("Firstname:");
String fn = TextIO.getlnWord();
TextIO.put("Lastname:");
String ln = TextIO.getlnWord();
Date date = DateFunctions.scanDate();
int pos = link.count;
Person item = new Person(fn,ln,date,pos);
add(item);
break;
case 3:
break;
case 4:
TextIO.putln("sort by:\n1) Firstname\n2) Birth\nall other values: lastname");
switch(TextIO.getInt()){
case 1:
break;
case 2:
break;
default :
break;
}
break;
case 5:
break;
case 6:
break;
case 0:
TextIO.put("Thank you for using the SimplePersonDatabase.");
break;
case 99:
break;
default :
TextIO.put("illegal option.");
break;
}
}while(option !=0);
}
public static boolean add(Person personadd) {
personadd.id = nextPersonId;
++nextPersonId;
list.add(personadd);
return true;
}
}
Your list is working well (I tried + or -)
import java.util.Arrays;
import java.util.Date;
class Person { // Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
the list
public class MyList {
int MAX_LIST = 20;
Person[] persons;
int count;
public MyList() {
persons = new Person[MAX_LIST];
count = 0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
System.out.println("enlarging");
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
public Person get(int i) {
return persons[i];
}
public static void main(String[] args) {
MyList list = new MyList();
for (int i=0; i<1000; i++) {
list.add(new Person("fn"+i,"sn"+i,new Date(),i));
System.out.println(list.get(i) + " " + list.count);
}
}
}
the problem is in the "go" function, why you are using link and then you add in list?

Class Constructor Problems While Doing A Linear Search Across Two Classes

Im creating a program that is supposed have the user enter a student name and see if it exist in the student array using a linear search method. The student array is in a different class and im having trouble creating a constructor i have tried many things and its not working can someone point me in the right direction.
My linear search class is
import java.util.*;
import java.util.Scanner;
public class LinearSearch {
public int find(Student [] a, String nm) {
for (int i = 0; i < a.length; i++) {
if (a[i].equals(nm)){
return i;
break;
}
else{
return -1;
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student [] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}
My Student class is
import java.util.*;
public class Student {
public Student(){
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
}
You defined a constructor with no argument:
public Student() {
}
But you're invoking a constructor which needs a String as argument:
studentArray[0] = new Student("Mel");
So, your constructor should have a String as argument:
public Student(String name)
And you should probably store this name as a field in the Student class:
private String name;
public Student(String name) {
this.name = name;
}
Note that there is no way that a Student instance could be equal to a String instance. You should provide a getter method for the name, and compare the entered String with the name of the student, instead of comparing it with the student itself.
import java.util.*;
public class Student {
private String name;
public Student(String name){
this.name = name;
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
public String getName(){
return name;
}
}
and of course in the compersion you'll need to do:
f (a[i].getName().equals(nm)){
public class Student {
private String studentName;
private Student[] studentArray;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Student[] getStudentArray() {
return studentArray;
}
public void setStudentArray(Student[] studentArray) {
this.studentArray = studentArray;
}
public Student(){
studentArray = new Student[3];
}
public Student[] getArray() {
Student st1 = new Student();
st1.setStudentName("mel");
Student st2 = new Student();
st2.setStudentName("Jared");
Student st3 = new Student();
st3.setStudentName("Mikey");
studentArray[0]=st1;
studentArray[1]=st2;
studentArray[2]=st3;
return studentArray;
}
}
the above code is your Student class. there is no need to create a constructor though. but because you would like it i put it in the code.
the LinearSearch class is as follow:
public class LinearSearch {
private int i;
public int find(Student[] a, String nm) {
for ( i = 0; i < a.length; i++) {
if (a[i].getStudentName().equals(nm)) {
break;
} else {
i = -1;
}
}
return i;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student[] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}

Categories