Array project seems to only print out null - java

The program is supposed to assign random values to the Student objects in the studentArr array.
Right now it is only printing out null values. Ive tried several different print methods.
I'm pretty sure its something wrong with either my method that is supposed to fill out each student object's attributes, or with my print statement.
import java.util.*;
public class Lab6Excercise
{
String[] first={"Rick","Morty","Moriarty","Samus","Promethius","Geiger","Moriarti","Bob","Taco",
"Asparagus","Shoes","Potato","Dirty","Dan","Spongebob","Space","Nova","Illadin","Orange","Electron"};
String[] last={"PoopyButthole","Red","Mantis","Toboggan","Oak","Elm","Dumbledore","Potter","Spice","Toothbrush","Argon",
"Blitz","LazerWolf","Mc-BigMac","King","Queen","Spork","Petrolium","Apple","Trash"};
//no syntax errors if set to static, but prints out null for everything.
//problem here or in calling array to print?
public static Student[] studentArr= new Student[20];
public Lab6Excercise(){
initializeArray();
}
public void initializeArray(){
for(int i=0; i>20; i++){
//this one seems correct but it cant find the symbol method- setStudentID etc. methods
// online it said to try (Student)studentArr.setStudentID(id())
//which explicitely casts it
//seems to work
//http://stackoverflow.com/questions/29328569/setting-values-to-an-array-of-objects
studentArr[i]= new Student();
studentArr[i].setStudentID(id());
studentArr[i].setFirstName(First());
studentArr[i].setLastName(Last());
studentArr[i].setGrade(Grades());
//other way?probably wrong
//studentArr[i]= new Student(studentArr.id(),
//studentArr.First(),
//studentArr.Last(),
//studentArr.Grades());
}
}
public Student[] getStudentArr(){
return studentArr;
}
//do i even need this?
//public Lab6Excercise getLab(){
// return lab;
//}
public static void main(String[] args){
//randomly generate double grade, student id;
//create 2 arrays, first name, last name. pull randomly for name generation
//necessary? how do i
Lab6Excercise lab= new Lab6Excercise();
//prints out hash or something
//System.out.println(lab.studentArr.toString());
//prints out nulls
// System.out.println(Arrays.deepToString(studentArr));
for(int i=0; i<studentArr.length; i++){
System.out.println(studentArr[i]);
}
}
public int id(){
int ID=1+(int)(Math.random()*((100-1)+1));
return ID;
}
public String First(){
Random random= new Random();
int index= random.nextInt(first.length);
return first[index];
}
public String Last(){
Random random= new Random();
int index= random.nextInt(last.length);
return last[index];
}
public double Grades(){
double grade=0+(double)(Math.random()*((4-1)+1));
return grade;
}
}
and the object class
import java.util.Random;
public class Student
{
private int studentID;
private String firstName;
private String lastName;
private double grade;
// no-argument constructor calls other constructor with default values
public Student()
{
this( 0, "", "", 0.0 ); // call four-argument constructor
} // end no-argument Student constructor
// initialize a record
public Student( int id, String first, String last, double grade )
{
setStudentID( id );
setFirstName( first );
setLastName( last );
setGrade( grade );
} // end four-argument Student constructor
// set student ID number
public void setStudentID( int id )
{
studentID = id;
} // end method setStudentID
// get student ID number
public int getStudentID()
{
return studentID;
} // end method getStudentID
// set first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// get first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// get last name
public String getLastName()
{
return lastName;
} // end method getLastName
// set grade
public void setGrade( double gradeValue )
{
grade = gradeValue;
} // end method setGrade
// get grade
public double getGrade()
{
return grade;
} // end method getGrade
public static int getRandom(int[] array){
int rnd= new Random().nextInt(array.length);
return array[rnd];
}
public String toString(){
return "First name: "+firstName + "Last name: " + lastName+ "ID: "+ studentID+ "Grade: " + grade+"\n";
}
}

You never initialize your array, because your for loop indexing is wrong.
for (int i = 0; i > 20; i++)
This says: for i starting at 0, run the following code if i is greater than 20, incrementing the value of i by 1 each time. Since i starts out already being less than 20, it is never greater than 20, and the code never runs. Instead, do the following, making your run-condition i less than 20:
for (int i = 0; i < 20; i++)
Or, better yet:
for (int i = 0; i < studentArr.length; i++)
For more details on the syntax of the for statement, check out the Java documentation.

It's a simple error in your for loop in the initialize array method. The statement: i >20 is the condition under which the loop will execute. But if i starts as 0 it will never be 20 and the loop will never execute. Just change the condition (which is i >20 right now) to i < 20 and it will work. :)

Related

Referencing the array variables in the Reference class, sorting it using another method, and invoking the sorted values in the case statement

I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.

Insert two arrays in one using two methods for each array

i want to create 3 arrays with objects.The two arrays(pin and age) i want to put them on one array named Alltogether.I use from each method to return me an array i dont know if this is right i try it.In the end i want to systemout only the array that has all this.
package worklin1;
public class worklin1{
static int N; //from keyboard i have a class userinput
private String Name; // name
private int age; // age
private int costVehicle; //vehicle
public worklin1(){}
public worklin1(String Name, int Age, int cost, String name) {
Name=name;
Age=age;
costVehicle=cost;
}
// Access methods
public String getName(){
return Name;
}
public int getAge(){
return age;
}
public int getcostVehicle(){
return costVehicle;
}
// Mutator methods
public void setName(String name){
Name=name;
}
public void setSurname(String age){
age=age;
}
public void setcostVehicle(int cost){
costVehicle=cost;
}
public String toString() {
String s=name+" "+age+", "+cost+"\t";
return s;
}
public static void main(String[] args){ //main
int[] pin= new int[N]; // the first array
int[] age=new int[]; // the second array.i dont know why it is false this array maybe i use an object as name for an array thats why its false.
Allmethodtogether[] pin = new Allmethodtogether[N]; // Allmethodotogether is an array.It has the combination of age and the cost.The N is just a number i give from keyboard i dont care about this right now.I just wanted to focus on my problem which is how to combine the two methods(which they give me each one 2 arrays and i will add them in this array name Allmethodtogether).
for (int i = 0; i < 10; i++) { // i want to put in an array all the arrays from the methods so i start the counting from 0 until 10.Until the 10 will be saved the pin and after 10 will be saving the array age
Allmethodtogether[i] = new Vehcost();
Allmethodtogether[i+10] = new AllAge();
} //finished //Now i want to display those arrays and i am trying this .
int y; // i create a variable to save my results from the method
y=worklin1.Vehcost(int[] pin); // i take the result from the method Vehcost
System.out.println("Appear all array"+y ); //i want to appear the array.Did i create and an array with objects?
int k; // i do the same thing as the other
k=worklin1.Allage(int[] age);
System.out.println("Appear all array"+k);
} // end main
public static int Vehcost(int[] pin ) { //starting first method 1
int cost = 0;
for(int i =0; i < pin.length; i++) {
cost += pin[i].getcostVehicle();
pin[i]=getname()+ cost; //i want to save to pin the names and the cost of each one
}
return pin[i]; // i want to return the array pin
}//end method 1
public static int allAge(int[] age ) { //second method
if(getage() >18 ){ //if age is >18 only then will going to save on the array
for(int i =0; i < age.length; i++) {
age += age[i].getage();
}
}
return age; // i want to return the array age
}// end method 2
}

JAVA Inheritance student, undergrad and gradstudent code

For a class project I was asked to create three codes.
Student Class
First, the student class containing three Parameters.
Name(String)
TestScores( int array),
Grade(String).
An empty Constructor. sets the Name and Grade to empty Strings. The TestScores Array will be initialised with three zeros.
Another Constructor(String n, int[] tests, String g)- This will set the name, testScores, and grade.
Three methods:
getName() to return the name
getGrade() to return the grade
setGrade() to set grade
getTestAverage() to return the average of the test scores.
This is where I am having difficulty The method computeGrade(), which, if the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail".
The second class is called UnderGrad. This class is a subclass of Student.
We had to create an empty Constructor and another Constructor (String n, int[] tests, String g).
We were instructed to override the computeGrade() method so that an UnderGrad() student must get a 70 or higher to pass.
The third class is the GradStudent a subclass of Student.
We have to create 1 instance variable, int MyGradID, and an empty constructor, which calls super, and set the IDs to 0.
And another constructor (String n, int[] tests, String g, int id)- Remember to call the super constructor and set ID.
Again where I am having challenges. We had to write the method getId(), to return the ID number. Again we needed to override the computeGrade() method And, if the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail". But if the test average is higher than 90, the grade should be "Pass with distinction".
I have great difficulty with this task. I attached the GradStudent code. Can you find the errors please? I don't fully understand how to override the superclass private instance variables.
public class GradStudent extends Student {
private int MyGradID;
public void GradStudent() {
super();
MyGradID = 0;
}
public void GradStudent(String n, int[] tests, String g, int id) {
super(n, tests, g);
MyGradID = id;
}
public int getId() {
return MyGradID;
}
#Override public void computeGrade() {
if (testScores.getTestAverage() >= 65) {
super.setGrade("Pass");
} else if (testScores.getTestAverage() > 90) {
grade = "Pass with distinction";
}
}
}
This is my Student class. I'm not sure if I am referencing my super class correctly, so I am adding it. Hopefully you can explain it to me.
public class Student {
private String name;
private int[] testScores = new int[3];
private String grade;
public Student() {
name = "";
grade = "";
testScores[0] = 0;
testScores[1] = 0;
testScores[2] = 0;
}
public Student(String n, int[] tests, String g) {
name = n;
testScores = tests;
grade = g;
}
public String getName() {
return name;
}
public String getGrade() {
return grade;
}
public void setGrade(String newGrade) {
grade = newGrade;
}
public int getTestAverage() {
int average = 0;
int count = 0;
for (int testScore : testScores) {
count++;
average = average + testScore;
}
return average / testScores.length;
}
public void computeGrade() {
grade = "Fail";
if (this.getTestAverage() >= 65) {
grade = "Pass";
}
}
}
This question simply wouldn't exist if you had an IDE (or, looked at the feedback from compile). I pasted the code into Eclipse and out popped a lot of problems.
Let's look at GradStudent.
public class GradStudent extends Student {
private int MyGradID;
// Constructors do not return anything.
public GradStudent() {
super();
MyGradID = 0;
}
// Again, constructors do not return anything.
public GradStudent(String n, int[] tests, String g, int id) {
super(n, tests, g);
MyGradID = id;
}
public int getId() {
return MyGradID;
}
// Okay. Override annotation in place. Now, computeGrade() needs to get its data from someplace. Fortunately, we
// have a method in Student to do that for us. That method is called 'getTestAverage()'. You do not need to
// reference the array created in 'Student'.
#Override public void computeGrade() {
int testAverage = getTestAverage();
if (testAverage >= 65) { // Evaluate against that testAverage. There is no method (or parameter) associated
// with an array that will compute its average.
setGrade("Pass");
} else if (testAverage > 90) {
setGrade("Pass with distinction");
}
}
}
The Student class is just fine (though count in getTestAverage() is a pointless variable which doesn't do anything and an int[] is created with all values being initialised to 0).
Now I would question why the instructor would have told you to create a constructor to set the grade... when you don't actually know what the grade is... but whatever.
Where are you having trouble with the computeGrade() method in Student? It seems fine to me. The problem in GradStudent is fixed given the changes made above.
What jumps out at me is
if(testScores.getTestAverage>=65)
Try changing that to
if(testScores.getTestAverage()>=65)
Easy mistake to make. Hope this helps!
Edit - I see that twice.
Also, I don't think constructors should have a return type void (or any) though I could be wrong.

Add static method to class takes array Athletes as argument and returns total nums of medals won by all

i already have the athelete class and i just dont know how to go about the rest of the problem ive been trying to do things that havent work at all but heres what i have for now. im still a beginner this is my first semester taking java so i may not understand some of the things you guys will add so if u can please explain.
This is what they are asking for me to do.
Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. test in method.
package homework;
import java.util.Arrays;
public class Athlete {
private String name; // the name of the athlete
private String sport; // the sport the athlete does
private int numMedals; // the number of medals that the athlete has won
// constructor
public Athlete(String n, String s, int num) {
name = n;
sport = s;
numMedals = num;
}
// getters and setters for all instance variables
// (also called accessors and mutators)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getNumMedals() {
return numMedals;
}
public void setNumMedals(int numMedals) {
this.numMedals = numMedals;
}
/* Returns a String with information about the athlete.
*/
public String toString() {
return name + " does " + sport + " and has won " + numMedals + " medal(s).";
}
public static void AthMedals(int[][]numMedals){
for(int i = 0; i < numMedals.length;i++){
int total = 0;
for(int j = 0; j < numMedals.length; i++);
total = numMedals.getNumMedals();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Athlete SA = new Athlete("Socrates","Baseball",5);
Athlete CC = new Athlete("Cesar","Baseball",3);
Athlete JA = new Athlete("Juan","Soccer",2);
System.out.println(SA);
System.out.println(CC);
System.out.println(JA);
System.out.println("SA has " +SA.getNumMedals()+ " medals.");
}
}
}
The assignment is to write a method like
public static int sumOfAllMedals(Athlete[] all)
which returns all[0].numMedals + all[1].numMedals + ... + all[n].numMedals.
I assume AthMedals is your attempt at doing this, but it's in fact only consuming processing power while not doing anything.
I'm not gonna do your homework for you, but here's a hint:
public static int sumOfAllMedals(Athlete[] all)
{
int total = 0;
// For every Athlete in `all`, add the number of medals (s)he's won
// Should be four lines at most ;)
return total;
}
The static method have to iterate the array and add each medals to a final return variable.
static public int totalMedals(Athlete[] athelte) {
int totalMedals = 0;
for(int i=0;i<athelte.length;i++) {
totalMedals += athelte[i].numMedals;
}
return totalMeadls;
}

array of string in java

I want to solve this problem without using arraylist.
i want to add the contact to its specific index in the array of strings. And then display all the added contacts in string format seperated by commas.
My code gives the result of only last added contract:
Contact [first=Bob, last=Moore, number=555-9756]
where is the problem in my code?
Is there any idea how to solve???
This class consist of the main method:
This is the main class:
public class ExampleApp {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook("Personal book");
System.out.println( pb.getName() );
pb.add("Alice", "Green", "555-1234");
pb.add("Mary", "Smith", "555-6784");
pb.add("Bob", "Moore", "555-9756");
System.out.println( pb.toString() );// here i want to display all the contracts seperated by commas
System.out.println( pb.first() );// first contract
System.out.println( pb.get(2) );// second contract
String toBeFound = new String("Moore");
System.out.println( pb.find(toBeFound) );// display the found contract
}
}
This is the phonebook class:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
/**
* Create a new phonebook with given name
*/
public PhoneBook(String name) {
this.name = name;
}
/**
* Return the phonebook name
*/
public String getName() {
return name;
}
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
for(int i=0;i<MAX;i++){ // i added for each array index the contracts strings
contracts[i]= c.toString();
}
}
/**
* Return the first contact
*/
public String first() {
return get(1);
}
/**
* Return the i-th contact (supposing that first
* index is 1)
*/
public String get(int i) {
String s =contracts[i].toString();
return s;
}
/**
* Return a string containing the list of textual
* representation of all contacts, separated by ", ".
* List starts with "("and ends with ")"
*/
public String toString() {
String s= " ";
for(int i=1;i<MAX;i++){ // here i tried to display the string looping the array
s=contracts[i].toString();
}
return s;
}
/**
* Return the textual representation of first
* contact containing "needle"
*/
public String find(String needle) {
//TODO: to be implemented
return null;
}
}
This is the contact class :
public class Contact {
public String first;
public String last;
public String number;
public String[] contacts;
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
You can use ArrayList for it. It will help you really much and you should make your veriables private.
private String first;
private String last;
private String number;
private ArrayList<String> list = new ArrayList<String>();
for(String pointer : list){
}
or you can make contact saver ArrayList
private ArrayList<Contact> list = new ArrayList<Contact>();
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public void add(String first, String last, String number){
c=new Contact(first,last,number);
list.add(c);
}
and you can access all veriables like that list.get(i).first.
You can save your contact class and contracts array in arraylist and it will give you more power to access. If you want to display your ArrayList, which index is not important, you need only ++i for it.
I changed your class look this:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
private int count = 0;// saved last index of array
public PhoneBook(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(String first, String last, String number) {
c = new Contact(first, last, number);
contracts[count] = c.toString(); // save your String inside of last index++
count++;
}
public String first() {
return get(1);
}
public String get(int i) {
String s = contracts[i].toString();
return s;
}
public String toString() {
for (int i = 0; i < MAX; i++) {
if (contracts[i] != null)
System.out.println(contracts[i].toString());
}
return "";
}
public String find(String needle) {
return null;
}
}
public class Contact {
public String first;
public String last;
public String number;
public Contact(String first, String last, String number) {
this.first = first;
this.last = last;
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
//Personal book
//Contact [first=Alice, last=Green, number=555-1234]
//Contact[first=Mary, last=Smith, number=555-6784]
//Contact [first=Bob, last=Moore, number=555-9756]
you always delete your last toString method. Your Add method is wrong. You always turn 0 and write again inside of array.
You should keep track of the last contact added to your array :
private int lastIndex = 0; // index of first available index of the array
...
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
if (lastIndex < MAX)
contracts[lastIndex++]= c.toString();
}
Some other issues with your code :
/**
* Return the first contact
*/
public String first() {
return get(1); // should be get(0)
}
Calling toString() for contracts[i] is redundant, since it's already a String. Perhaps you meant to store Contact instances instead of Strings in your array? That would make more sense.
Add an extra variable static int Last = 0; To track how many contact you have added and update the add function as .
public void add(String first, String last, String number){
if(Last>=MAX){
System.out.println("Error in adding\n");
}
else{
c=new Contact(first,last,number);
contacts[Last] = c.toString();
Last++;
}
}
Change Tostring() for loop to last. So that you will be printing only added contact .In your case you are printing upto MAX that is wrong when less no of contacts are added.
You have to pass i=0,1,2,...,MAX-1 to get(i) function . Array is Zero(0) based indexed.
So, the problem you are having is that you always retrieve the last contact, regardless of which one you try to get. This is because when you add a new contact, you are actually replacing ALL the contacts, making them all the same. You are getting the correct contact from the phonebook, but they ALL have the same value.
To fix it, do the following:
public class PhoneBook
{
int contactsAdded = 0; // Add an integer to store how many contacts you have added
Contact[] contacts = new Contact[MAX]; //Change this to Contact array, not string
//Contact c; //You can remove this line
//Rest of your code
}
public void add(String first, String last, String number)
{
//Only add if the number of contacts is less than the max
if (contactsAdded < MAX)
{
//Construct the new contact when you use it.
contacts[contactsAdded] = new Contact(first, last, number);
contactsAdded++;
}
}
Not sure if I understood all of your code right, but I think you are overwriting all other contacts in your phone book:
public void add(String first, String last, String number){
c=new Contact(first,last,number); //(1)
for(int i=0;i<MAX;i++){ //(2)
contracts[i]= c.toString();
}
}
At position (1) a new Contact object is created and assigned to c. In the next step (2), you loop through the array and assign the info contained in c (the latest contact added) to all already entries in the contracts array.
Independent from your problem, I suggest that you replace the array of a fixed size with i.e. an ArrayList of type Contact. Adding entries to this list, iterating, sorting etc is very easy.

Categories

Resources