How to check matching int values/ String values in an array? - java

We are asked to write a code and enter name and age for 4 people. After that, we are required to find whether any of the age match each other. Later the question asks whether the names match, but I haven't gotten to that part just yet.
I tried making an array so that I can store the values of the inputted ages. I cannot figure out how I can compare age's values with other elements in the array.
package person;
public class Person
{
static int personAge;
String personName;
public void setName(String name) {
name=personName;
}
public String getName() {
return personName;
}
public void setAge(int age){
age=personAge;
}
public int getAge() {
return personAge;
}
}
package person;
import java.util.Scanner;
public class PersonMain extends Person
{
static int [] ageStore=new int [4];
public static void main(String[] args)
{
for(int i=1;i<5;i++)
{
Person person= new Person();
person.setName(person.personName);
System.out.println("Please enter name for person " + i );
Scanner input= new Scanner(System.in);
person.personName=input.next();
Scanner keyboard= new Scanner(System.in);
System.out.println("Now, input " + person.personName + "'s age" );
person.setAge(personAge);
personAge=keyboard.nextInt();
ageStore[i]=person.personAge;
System.out.println("Age is " + ageStore[i]);
}
//what can help me compare the values of int age in the array?
}
}
The end goal here is to print out the names of people that have the same age.

Of course they all have the same age: personAge is declared as static. Remove the static keyword in front of the declaration.
UPDATE: and yes, use getters and setters instead of accessing fields directly.
To summarise:
remove the static keyword in front of personAge declaration,
declare personAge and personName as private to ensure you use the getters and setters,
remove the extends Person in class PersonMain,
in method main, use the getters and the setters instead of accessing the fields directly.
UPDATE 2: Oh! yes! some more issues:
in the setters, assign the argument to the field, not the other way around (personName=name; and personAge=age).
variable i should go from 0 to 3 because the array is declared with a size of 4: for(int i=0;i<4;i++) or better: for(int i=0;i<ageStore.length;i++),
move the Scanner declaration and initialisation out of the loop, and use only one of them.

If you are collecting information that is required for later processing, you need to store all of that information.
At the moment, you are storing the ages in an array, but throwing away the names.
So, instead of keeping an age array like this:
static int [] ageStore=new int [4];
... try keeping an array of Persons. Plus you don't need to keep them outside the main method. So, in the main method:
Person[] persons = new Person[4];
Also, fix your Person class so that the age is not static and the variables are private:
private int personAge;
private String personName;
Now create a single scanner because you don't need one per loop or per input:
Scanner input= new Scanner(System.in);
Then create your loop, but run it from 0 to less than the length of the array to fill (because indexes in Java start at 0):
for (int i = 0; i < persons.length; i++) {
Then make a new Person object to populate:
Person person = new Person();
Then collect the name and age from the user (remembering that i is 1 less than what you want to show to the user):
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
And add the person to the array:
persons[i] = person;
Then you can close your loop.
So far you should have:
package person;
import java.util.Scanner;
public class PersonMain {
public static void main(String[] args) {
Person[] persons = new Person[4];
Scanner input= new Scanner(System.in);
for (int i = 0; i < persons.length; i++) {
Person person = new Person();
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
persons[i] = person;
}
// matching code will go here
}
}
Now we need to do the matching part.
One way of doing that is to check each item against all the items after it in the list. That would look like this:
for (int i = 0; i < persons.length - 1; i++) { // until 'persons.length - 1' because if we look at the last item, it has nothing left to compare against
Person currentPerson = persons[i];
for (int j = i + 1; j < persons.length; j++) { // start at the next index (i + 1)
if (currentPerson.getAge() == persons[j].getAge()) { // we have an age match
System.out.println(currentPerson.getName() + " has the same age as " + persons[j].getName());
}
}
}

Related

How to retain an object in an array of objects in Java

I'm not sure how to ask this question. I have to write a program that has 2 classes: one store the data and one call to display the data. The data is Student's name and the names of his/her 4 courses. But I have to put this in a loop for the user to input at least 3 records. If the user doesn't enter a student's name (or name = blank) get out of the loop and display the info entered.
Example:
John Doe MATH 101 ENGL 101 READ 101 COMP 101
Jane Doe PHYS 101 CHEM 101 PSYC 101 ACCT 101
Mary Doe PHED 101 HIST 101 CALC 101 POLS 101
What I'm trying to do is make each of the students' record an object and store those 3 objects in an array of objects then display it.
Below is my code:
import java.util.Scanner;
public class UserInterface {
public static void main(String[] args) {
//Create a scanner
Scanner input = new Scanner(System.in);
//Create an object from Business class
Business b = new Business();
//Declare variables
final int NUMBER_OF_COURSES = 4;
String[] coursesName = new String[4];
Business[] businessArray = new Business[3]; //Declare a array of objects
for (int counter = 0; counter < businessArray.length; counter++) {
//Prompt user to input name
System.out.println("Enter student's name: ");
b.setName(input.nextLine());
for (int i = 0; i < NUMBER_OF_COURSES; i++) {
System.out.println("Enter " + b.getName() + "'s course number " + (i + 1));
coursesName[i] = input.nextLine();
}//end of for(i)-loop
b.setCourses(coursesName);
businessArray[counter] = b;
System.out.println(businessArray[counter]); //Here it display correctly for each round
}//End of for(counter)-loop
for (int pa = 0; pa < businessArray.length; pa++)
System.out.println(businessArray[pa]); //but here it displays 3 records of the last entry
//so my question is how do I retain each entry in its own object and
//adds it to the array of objects?
//I know that b gets overwrite by the last data entered because
//it is just a pointer to that object.
input.close();
}//End of main method
}//End of class UserInterface
The other class:
public class Business {
//Declare variables
private String name;
private String[] courses = new String[4];
//Default Constructor
public Business(){
}
//getter for student's name
public String getName() {
return name;
}
//setter for student's name
public void setName(String name) {
this.name = name;
}
//getter for courses' name
public String[] getCourses() {
return courses;
}
//setter for courses' name
public void setCourses(String[] courses) {
this.courses = courses;
}
}//End of class Business
I know my codes are not good. But I'm required to have getters and setters for each variable in this Business class.
Move your creation of the Business object into the for loop:
for (int counter = 0; counter < businessArray.length; counter++) {
Business b = new Business();
// ...
}
Right now, every entry in the array points to the same object, so you're overwriting the values in it repeatedly. Moving the creation into the loop means you'll have a different object for each slot of the array.
String retainCourse(int pointer){
return this.courses[pointer];
}
Add this function to your business class.
You should overwrite the .toString() method of the class to get the expected result.
In a for loop it is a better practice to get the current object and set it as a temporary variable casted to the exact class! Business current = (Business) businesses[i];

Getting the highest number from an ArrayList of different data types

I am working on a program that prompts the user for a Name, An age and a Gender. The program is supposed to give me a list of Name, Age and Gender from each input AND ALSO tell me who is the oldest person from that list. I have created an ArrayList to hold the values and I am ok using an enhanced loop to print out the names, ages and genders. What I am having trouble with is getting the program to print out the highest (oldest) number from the ArrayList. I have created an alternative way to do it by creating an Additional ArrayList with only the ages but I don't seem to find a way to get this from the Original ArrayList. This alternative way gives me only the highest number from the extra array but if I wanted to print the name of the oldest person with his/her age, it won't work. I will appreciate some help to figure this out. I am really new to Java.
Here my code so far:
From Person Class:
package person;
public class Person {
private String name ;
private int age;
private String gender;
private int oldestPerson;
public Person(String name1, int age1, String gender1){
name = name1;
age = age1;
gender = gender1;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String getGender() {
return gender;
}
public void changeName(String newName){
name = newName;
}
public void changeAge(int newAge){
age = newAge;
}
public void changeGender(String newGender){
gender = newGender;
}
public int getOldest(int max){
if (age > max){
max = age;
}
return oldestPerson;
}
}
From personTester class:
package person;
import java.util.Scanner;
import java.util.ArrayList;
public class personTester {
public static void main(String [] args){
ArrayList<Person> personList = new ArrayList<Person>();
ArrayList<Integer> personAges = new ArrayList<Integer>(); //extra array
boolean Done = false;
Scanner input = new Scanner(System.in);
while(!Done){
System.out.println("enter a name");
String name = input.next();
System.out.println("enter an age");
int age = input.nextInt();
System.out.println("enter a gender");
String gender= input.next();
personList.add(new Person(name, age, gender)); //put a person inside an arraylist
personAges.add(new Integer(age));
System.out.println("Press Y to exit or N to continue");
String choice = input.next();
if(choice.equalsIgnoreCase("Y")){
Done=true;
}
}
for(Person e :personList){
System.out.println("Name: "+e.getName() +" - Age: "+ e.getAge()+" -
Gender: " + e.getGender());
} // getting the highest number from the aditional array.
int max = 0;
for (int ages: personAges){
if (ages > max){
max = ages;
}
}
System.out.println("The oldest person in the list is " + max);
}
}
Imagine the following real-life scenario: There is a group of persons which don't know anything about each other, and you as bystander want to know who is the oldest. You can't ask a person: Are you the oldest? Because they don't know how old the other people in the group are.
Instead, you'll have to ask each person how old they are, and based on that determine yourself who is the oldest.
So in your code, the private int oldestPerson; field and public int getOldest(int max) method should be removed from Person. They don't know if they are the oldest, they can only give you their age.
And you (the programmer) should ask the age to all persons and determine based on that who is the oldest.
So change this part of your code:
int max = 0;
for(int ages : personAges){
if(ages > max){
max = ages;
}
}
System.out.println("The oldest person in the list is " + max);
To this:
int maxAge = 0;
for(Person p : personList){
int pAge = p.getAge();
if(pAge > maxAge){
maxAge = pAge;
}
}
System.out.println("The oldest person in the list is " + maxAge + " years old");
And you can also remove the ArrayList<Integer> personAges= new ArrayList<Integer>(); //extra array and personAges.add(new Integer(age));
Like this you are getting the ages from the Persons (using your getter getAge() and store it in maxAge).
You can use a Comparator to sort your list with age and get the oldest one, for example :
String choice;
do {
System.out.println("enter a name");
String name = input.next();
System.out.println("enter an age");
int age = input.nextInt();
System.out.println("enter a gender");
String gender = input.next();
personList.add(new Person(name, age, gender)); //put a person inside an
System.out.println("Press Y to exit or N to continue");
choice = input.next();
} while (choice.equalsIgnoreCase("Y"));
Collections.sort(personList, new Comparator<Person>() {
#Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
System.out.println("The oldest person in the list is " +
personList.get(personList.size()-1).getName() +
" His/Her age is " + personList.get(personList.size()-1).getAge());
I created a test list of Persons to illustrate my solution:
List<Person> persons = new ArrayList<>();
persons.add(new Person("Kees", 100, "M"));
persons.add(new Person("Kees", 0, "V"));
persons.add(new Person("Kees", 10, "V"));
persons.add(new Person("Kees", 1, "M"));
Then using Java 8 streams you can sort on the age of the Person (old to young by using reversed())and then get the first result:
Person oldest = persons.stream()
.sorted(Comparator.comparing(Person::getAge).reversed())
.findFirst().get();
Added a standard toString() method to your Person class to print the result
System.out.println(oldest);
Which now prints:
Person [name=Kees, age=100, gender=M]
An alternative way of printing the details of the list of persons uses forEach() instead of a for-loop
persons.forEach(p -> System.out.println(p.getName() + " " + p.getAge() + " " + p.getGender()));
one approach is to use the streams max method and pass in your own comparator:
ArrayList <Person> personList= new ArrayList<Person>();
Person oldestPerson = personList.stream().max(Comparator.comparingInt(Person::getAge)).get();
System.out.println("oldest persons name is: " + oldestPerson.getName() + " age is: " + oldestPerson.getAge());
I have created an alternative way to do it by creating an Aditional
ArrayList with only the ages but I don't seem to find a way to get
this from the Original array list.
This is quite frankly a horrible idea and you should forget that way as quickly as possible.
You are already iteration through your whole Person List. All you now have to do is create a variable that holds the Person with the highest Age (Lets call it highestAgePerson). In each iteration of your for loop you now check if the Person you are currently printing has an age that is higher than that of the Person denoted by your highestAgePerson, and set highestAgePerson to that new Person if thats the case.
final Person highestAgePerson = null; // initialize to null
for(Person e :personList){
System.out.println("Name: "+e.getName() +" - Age: "+ e.getAge()+" -
Gender: " + e.getGender());
if(highestAgePerson==null || highestAgePerson.getAge() < e.getAge()) {
highestAgePerson = e;
}
}
After that you will have the person with the highest Age inside the variable highestAgePerson and can print it and its attributes.

Displaying details of object arrays

Hi I'm very new to programming and I'm trying to write a programme in eclipse that does the following.
Create a Student class with 4 attributes: name, mark, course and phone number which are entered by the user.
Have a constructor which initialises those four attributes to the parameters passed in, and a display() method which displays the details of the Student.
Declares an empty array of 5 Student objects.
Create a Student object at the current position of the array using these variables.
Make a loop which calls the display() method of each Student in the array.
So far I've got the programme working to the point that it creates the array of 5 students and reads in the four different attributes from the user. But I can not figure out how to create a loop which calls the display method for each of the students.
This is my code so far..
import java.util.Scanner;
public class Student {
private String name, course;
private int mark, number;
public Student(String nameIn, String courseIn, int markIn, int numberIn)
{
this.name = nameIn;
this.course = courseIn;
this.mark = markIn;
this.number = numberIn;
}
public void display()
{
System.out.println("Name: " + this.name + " Course " + this.course + " mark: " + this.mark + " Number " + this.number);
}
public static void main (String[] args)
{
String[] Student = new String[5];
Scanner scanner = new Scanner(System.in);
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter course for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter number for student " + counter);
Student[counter] = scanner.nextLine();
}
for (int counter=0; counter< 5; counter++)
{
System.out.println(Student[counter].display());
}
}
}
PS sorry in advance if I have posted this question wrong. Its my first post and I couldn't find a similar question else where.
Thanks in advance.
Your current code doesn't create an array of Student, nor populate it correctly (each loop overwrites the former data) .
Also, the way you were calling display was wrong :
System.out.println(Student[counter].display());
First, you want to call display on an instance of Student, not on the class.
Second, you don't have to call System.out.println, because displayalready does this work (and calling System.out.println with the void parameter, because the display method returns nothing, will get you nowhere)
Try this way :
Student[] students = new Student[5];
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
String name = scanner.nextLine();
System.out.println("Enter course for student " + counter);
String course = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
String mark = scanner.nextLine();
System.out.println("Enter number for student " + counter);
String number = scanner.nextLine();
Student student = new Student(name, course, mark, number);
students[counter] = student;
}
for (int counter=0; counter< students.length; counter++)
{
students[counter].display();
}

Adding a Student to an Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have figured out how to gather the data from the user to make a new student in my array, but I am having trouble adding that information to the array. Please show me how I can add this data as a new Student object in the given code. Please reference to the AddStudent method.
import java.util.Scanner;
public class ArrayDemo {
static Student[] students;
private static void ViewStudents() {
for (int i = 0; i < students.length; i++) {
System.out.println(i + ") " + students[i].getLName() + ", " + students[i].getFName());
}
}
private static void ViewDetails() {
Scanner kb = new Scanner(System.in);
int i;
System.out.println("Who would you like to view?");
ViewStudents();
i = Integer.parseInt(kb.nextLine());
System.out.println("ANum:\t\t" + students[i].getANum());
System.out.println("\nAddress:\t" + students[i].address.getHouseNum() + " " + students[i].address.getStreet());
System.out.println("\t\t" + students[i].address.getCity() + ", " + students[i].address.getState() + " " + students[i].address.getZip());
System.out.println("\t\t" + students[i].address.getLine2());
}
private static void AddStudent() {
Scanner kb = new Scanner(System.in);
Student student = new Student();
String FirstName;
String LastName;
int HouseNum;
String Street;
String City;
String State;
int Zip;
String Line2;
System.out.println("\tInput Information");
System.out.println("\tFirst Name:");
FirstName = kb.nextLine();
System.out.println("\tLast Name:");
LastName = kb.nextLine();
System.out.println("\tHouse Number:");
HouseNum = Integer.parseInt(kb.nextLine());
System.out.println("\tStreet:");
Street = kb.nextLine();
System.out.println("\tCity:");
City = kb.nextLine();
System.out.println("\tState:");
State = kb.nextLine();
System.out.println("\tZip Code:");
Zip = Integer.parseInt(kb.nextLine());
System.out.println("\tExtra Information:");
Line2 = kb.nextLine();
System.out.println("\nStudent:\t" + LastName + ", " + FirstName);
System.out.println("ANum:\t\t" + student.getANum());
System.out.println("Address:\t" + HouseNum + " " + Street);
System.out.println("\t\t" + City + ", " + State + " " + Zip);
System.out.println("\t\t" + Line2);
//students.setAddress( HouseNum, Street, City, State, Zip, Line2 );
System.out.println("\tYour Student was Successfully Added");
}
private static void RemoveStudent() {
Scanner kb = new Scanner(System.in);
System.out.println("Who would you like to remove?");
ViewStudents();
for (int j = Integer.parseInt(kb.nextLine()); j < students.length - 1; j++) {
students[j] = students[j + 1];
}
students[students.length - 1] = null;
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int x = 40;
//students = new Student[0];
students = new Student[2];
students[0] = new Student("Thomas", "Emily");
students[1] = new Student("Bob", "Joe");
students[0].address = new Address(6614, "White Sands ln", "Hixson", "Tennessee", 37343, "");
students[1].address = new Address(66, "White ln", "Hson", "Tealamabaee", 373873, "");
do {
System.out.println();
System.out.println("Do you want to:");
System.out.println("\t0) View Students");
System.out.println("\t1) View Students' Details");
System.out.println("\t2) Add a Student");
System.out.println("\t3) Remove a Student");
System.out.println("\t4) Exit");
x = Integer.parseInt(kb.nextLine());
switch (x) {
case 0:
ViewStudents();
break;
case 1:
ViewDetails();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
break;
default:
}
} while (x != 4);
}
}
From what I can see, you are using the wrong kind of data structure. You seem to what to add a dynamic number of Students and an ArrayList would be a lot better and more appropriate than an Array. Then you can simply use the add method.
Remember, the size of an Array is immutable (it cannot change) so what you want in this case is definitely some sort of List, probably the ArrayList
If you insist on using an array, you would need to keep track of the number students already added and use that as an index (either as a global variable or pass it in as a parameter). But bear in mind that the nature of an Array means that you will hit a cap very quickly unless you set an very high capacity,
Believe me that there is no way you can add records to array without knowing how many records are there currently in your array. If you don't want another static variable to keep track number of records, you have to loop through the array till it is null.
static int numOfStudents = 0; //declare outside your main
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
if (numOfStudents < students.length){
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[numOfStudents] = stud;
numOfStudents ++;
}
}
An alternative solution which you would prefer. But this is bad in my opinion.
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
int index=0;
while(x<students.length && student[x] != null)
index++; //get position to add new student
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[index] = stud;
}
The easiest way without much change to your code would be to add a class variable called index next to the students array. This variable will keep track of the amount of students since arrays in Java have fixed length:
public class ArrayDemo
{
static Student[] students;
static int index = 0; // keeps track of the amount of students in the students array
// ... rest of your code
Then inside AddStudent() you add all the information you got from input to the current student at the index and update the index:
private static void AddStudent() {
// ... the code where you obtain user information
if(index < students.length) { // make sure there is room to add the user
Student student = new Student(/* add user information into the constructor */);
students[index] = student; // add the user at the index
index++; // update the index
} else {
System.err.println("No more room for students");
}
}
The code above assumes you have a constructor that accepts necessary user information.
Otherwise you can assign the information individually:
Student student = new Student();
student.firstName = firstName;
// ...
Or use setters like:
student.setFirstName(firstName);
If you do not with to use an index to keep track of amount of users and have a more dynamic way of storing the students, then I suggest using a List or some class that extends it such as an ArrayList
Your array has a fixed size of 2 elements. You could instead use a larger MAX value and (as the other answers have hinted) keep a variable that counts the actual number of array indices that are filled.
static int ARRAY_MAX = 10;
static Student[] students;
static int numStudents;
...
students = new Student[ARRAY_MAX];
numStudents = 0;
Adding a student would then look like...
students[numStudents] = new Student();
numStudents++;
...but its going to break when numStudents is greater than equal 10 (ArrayIndexOutOfBoundsException).
In this event you need to enlarge (resize) your array. In Java arrays have fixed size - resizing an array amounts to declaring a brand new array (with increased size), and then copying the old array into the new one. Use System.arraycopy to copy the contents from one array into the other.
You should really just use an ArrayList - behind the scenes this is what that object is doing.

How to print an array in Java

I have a Student class which has;
private String name;
private long idNumber;
and getters and setters for them.
I also have a StudentTest class which has three different methods, 1. to ask user for the size of the array and then to create an array of type Student, 2. to ask user to populate the array with names and ID numbers for as long as the array is, 3. to show the contents of the array.
The code I have so far is;
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
}
// Method that asks user for size of array.
public static Student[] createArray() {
System.out.println("Enter size of array:");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];
return students;
}
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
for(int i=0;i<array.length().i++) {
array[i] = new Student();
System.out.println("Enter student name: ");
Scanner userInputEntry = new Scanner(System.in);
array[i].setName(userInputEntry.next());
System.out.println("Enter student ID number: ");
array[i].setIDNumber(userInputEntry .nextLong());
}
}
// Method that displays contents of array.
public static void displayArray(Student[] array) {
}
}
How do I print the contents of the array back out to the user?
in class Student u can override toString():
#Override
public void toString(){
return "name: " + this.name;
}
and create a simple for loop
for(int i = 0; i < array.length; i++){
System.out.println(array[i].toString());
}
hope this helps a little
Override the toString method in Student class and then use https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])
use this in you display function if you don't want to override the toString method
for (int i = 0; i < array.length; i++) {
System.out.println("Student id : "+array[i].getIdNumber() + " Student name : " +array[i].getName());
}

Categories