I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.
I have a last Java homework task, this task is about employees,
my method should print employee's names and surnames, worked more than "n" years.
What I've done for now:
public class LastTask {
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static String displayEmployees(int n) {
return null;
}
}
class Employee {
private String surname;
private String name;
private String patronymic;
private String address;
private int employmentYear;
private int employmentMonth;
Employee(String surname, String name, String patronymic, String address, int employmentYear, int employmentMonth) {
this.surname = surname;
this.name = name;
this.patronymic = patronymic;
this.address = address;
this.employmentYear = employmentYear;
this.employmentMonth = employmentMonth;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getEmploymentYear() {
return employmentYear;
}
public void setEmploymentYear(int employmentYear) {
this.employmentYear = employmentYear;
}
public int getEmploymentMonth() {
return employmentMonth;
}
public void setEmploymentMonth(int employmentMonth) {
this.employmentMonth = employmentMonth;
}
}
I made a parametrised constructor for creating employees with multiple parameters, also made parameters encapsulated.
Have no clue what to do next, task says that I can use List/ArrayList, but after some time googling about it, I still can't understand how to implement a condition like if (employmentYear - currentYear >= n) then return employee1, employee4 for example.
Could you give me some tips?
Thank you for your attention.
You can create a static ArrayList and add those all employees to that ArrayList, and in displayEmployees method you can stream that list based on condition if employee EmploymentYear greater than n print details and add to another list so finally if you want you can just return count of employees or you can return List of employees also
public class LastTask {
static List<Employee> employee = new ArrayList<>();
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
employee.add(employee1);
employee.add(employee2);
employee.add(employee3);
employee.add(employee4);
employee.add(employee5);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static int displayEmployees(int n) {
List<Employee> finalList = new ArrayList<>();
employee.stream().forEach(emp->{
if(emp.getEmploymentYear()-Year.now().getValue()>=n) {
System.out.println("Employee Name : "+emp.getName()+" Sur Aame : "+emp.getSurname());
finalList.add(emp);
}
});
return finalList.size();
}
}
If you are looking for a way to find "worked more than 'n' years", this might help you.
Calendar.getInstance().get(Calendar.YEAR) - employmentYear >= n
Add a proper toString() method in the Employee class to get the desired output, apart from that I have used the filter() method from the Stream object to filter through the Employee objects. I am passing the number of years worked as an input parameter and calculating the years served in employment from the employmentYear field.
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
public class LastTask {
private static List<Employee> listEmps;
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
listEmps = new ArrayList<>(Arrays.asList(employee1,employee2,employee3,employee4,employee5));
//display employee details of employees who worked more than 17 years.
displayEmployees(17);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static void displayEmployees(int n) {
int year = Calendar.getInstance().get(Calendar.YEAR);
listEmps.stream()
.filter(emp ->{
return year - emp.getEmploymentYear() > n;
})
.collect(Collectors.toList())
.forEach(System.out::println);
}
}
class Employee {
private String surname;
private String name;
private String patronymic;
private String address;
private int employmentYear;
private int employmentMonth;
Employee(String surname, String name, String patronymic, String address, int employmentYear, int employmentMonth) {
this.surname = surname;
this.name = name;
this.patronymic = patronymic;
this.address = address;
this.employmentYear = employmentYear;
this.employmentMonth = employmentMonth;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getEmploymentYear() {
return employmentYear;
}
public void setEmploymentYear(int employmentYear) {
this.employmentYear = employmentYear;
}
public int getEmploymentMonth() {
return employmentMonth;
}
public void setEmploymentMonth(int employmentMonth) {
this.employmentMonth = employmentMonth;
}
#Override
public String toString(){
return "Employee details: " + this.name + this.surname + this.address + this.employmentYear;
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
The title says it all. This is a basic Customer class that the user inputs their name/age/street address/city/state/zip code and then the program formats the input and returns it to the user. When I run this class it skips over the 'Street Address' and goes straight to 'City' and thus I can't get it to let me input my street address.
I've looked at a fairly similar issue in this thread here: Java is skipping a line (Strings in a Scanner ??)
However I haven't derived anything from that that has helped me solve this issue. I'm sure its extremely basic but I'm just unable to catch it and don't have much time to work on this today, so any tips/help are appreciated!
public class Customer {
String name;
String streetAddress;
String city;
String state;
String zip;
int age;
//default constructor
public Customer() {
name = "Unknown";
streetAddress = "Unknown";
city = "Unknown";
state = "Unknown";
zip = "Unknown";
age = 0;
}
//constructor to accept values for the above attributes
public Customer(String n, String sAdd, String c, String st8, String z, int a) {
name = n;
streetAddress = sAdd;
city = c;
state = st8;
zip = z;
age = a;
}
//getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String displayAddress() { //returns a string with the complete formatted address
String showAddress;
showAddress = ("\nStreet Address: " + streetAddress + "\nCity: " + city + "\nState: " + state + "\nZip Code: " + zip);
return showAddress;
}
public String displayAddressLabel() { //returns a string with the customers name/age
String nameAgeAddress;
nameAgeAddress = ("Name: " + name + "\nAge: " + age);
return nameAgeAddress;
}
//main method
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//creating an object of the Customer class
Customer actualCustomer = new Customer();
//getting info for displayAddressLabel() and displayAddress
System.out.println("Enter your name: ");
actualCustomer.setName(scan.nextLine());
System.out.println("Enter your age: ");
actualCustomer.setAge(scan.nextInt());
//issue is here
System.out.println("Enter your street address: ");
actualCustomer.setStreetAddress(scan.nextLine());
System.out.println("Enter the city you live in: ");
actualCustomer.setCity(scan.nextLine());
System.out.println("Enter the state you live in: ");
actualCustomer.setState(scan.nextLine());
System.out.println("Enter your zip code: ");
actualCustomer.setZip(scan.nextLine());
System.out.println(actualCustomer.displayAddressLabel());
System.out.println(actualCustomer.displayAddress());
}
}
After this line:
actualCustomer.setAge(scan.nextInt());
you should call:
scan.nextLine();
because after scan.nextInt() there is a new line character left to be read (after inputting int you press Enter to confirm your input and you're missing to read it from your Scanner). Instead of writing these two lines:
actualCustomer.setAge(scan.nextInt());
scan.nextLine();
You might want to change it to:
actualCustomer.setAge(Integer.parseInt(scan.nextLine()));
It will get rid of new line character.
Im trying to create a student class, a course class and the main class. I am trying to add students to the course, and when students are added to the class the number of students in the course should increase, when the the code is run it should print the course details followed by the students in the course.
I have got the following code:
Main class:
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
Course class:
public class Course {
ArrayList<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*
*/
public Course(){
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents){
this.courseName = courseName;
this.teacher = teacher;
noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public static void addStudent(Student newStudent){
if(studentList.size()==noOfStudents){
System.out.println("The class is full, you cannot enrol.");
}
else {
studentList.add(newStudent);
}
}
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + this.noOfStudents;
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
public String getCourse(){
return this.course;
}
public String getPhoneNo(){
return this.phoneNo;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (JavaLecture3.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
public void setCourse(String course){
this.course = course;
}
public void setPhoneNo(String phoneNo){
this.phoneNo = phoneNo;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
* #param course String with course name
* #param phoneNo String with phone number
*/
public Student(int age, String name, String course, String phoneNo){
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html?is-external=true
Course.getNoOfStudents should just return studentList.size(). No need to maintain a separate variable.
To print a list of students (from Course):
for(int i=0;i<studentList.size();i++) System.out.println(studentList.get(i));
Since you initialized the array list in the Course class, you should add the students to it. You should create a method in Course that adds an object to the array list such as:
public void addStudent(Student s){
studentList.add(s);
noOfStudents++;
}
To add multiple students:
public void addStudents(Student[] students){
for(int i = 0; i < students.length; i++){
studentList.add(students[i]);
}
}
You're almost there, just use the .add method made for you in the array list.
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
course.addStudent(student);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
public class Course {
List<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
// Getters
public String getCourseName() {
return this.courseName;
}
public int getNoOfStudents() {
return this.noOfStudents;
}
public String getTeacher() {
return this.teacher;
}
// Setters
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents) {
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with
* defaults
*
*/
public Course() {
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
*
* #param noOfStudents
* integer
* #param courseName
* String with the Course name
* #param teacher
* String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents) {
this.courseName = courseName;
this.teacher = teacher;
this.noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public void addStudent(Student newStudent) {
if (studentList.size() == noOfStudents) {
System.out.println("The class is full, you cannot enrol.");
} else {
studentList.add(newStudent);
}
}
#Override
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + studentList.size();
}
}
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public String getCourse() {
return this.course;
}
public String getPhoneNo() {
return this.phoneNo;
}
// Setters
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
if (JavaLecture3.DEBUG > 3)
System.out.println("In Student.setName. Name = " + name);
this.name = name;
}
public void setCourse(String course) {
this.course = course;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student() {
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
*
* #param age
* integer
* #param name
* String with the name
* #param course
* String with course name
* #param phoneNo
* String with phone number
*/
public Student(int age, String name, String course, String phoneNo) {
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
*
* #param gender
*/
public Student(String gender) {
this(); // Must be the first line!
this.gender = gender;
}
protected void finalize() throws Throwable {
// do finalization here
instances--;
super.finalize(); // not necessary if extending Object.
}
public String toString() {
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Create course object
Course course = new Course("CSE", "Tom", 5);
Scanner scanner = new Scanner(System.in);
String cmd = "Yes";
while(cmd.equals("Yes")){
Student student = new Student();
System.out.print("Enter a new student? ");
cmd = scanner.next();
if (cmd.equals("Yes")){
//Read student name
System.out.print("Enter a student name: ");
String name = scanner.next();
student.setName(name);
//Read student Age
System.out.print("Enter a student age: ");
int age = scanner.nextInt();
student.setAge(age);
//Read student Course
System.out.print("Enter a student course: ");
String stdent_course = scanner.next();
student.setCourse(stdent_course);
//register the student to the class
course.addStudent(student);
}
}
scanner.close();
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course.toString());
System.out.println();
}
}
I reworked a bit your toString() method from Course class. This should print the list of students attending a class.
public String toString (){
String ret_value = "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo + " Students attending this course:";
for (Student student: studentList) {
ret_value = ret_value + " " + Student.getName();
}
return ret_value;
}
something like this but using 2D array to input Name, age, gender and to find the oldest person that the user inputted.
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
You Should create a Person class which will have properties like age, name, gender and should implement Comparable interface.
Person class
class Person implements Comparable{
String name;
String gender;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public int compareTo(Object arg0) {
Person p = (Person)arg0;
return p.getAge() - this.getAge();
}
}
Main class
List<Person> personList = new ArrayList<Person>();
while(true) {
Person p =new Person();
Scanner stdin = new Scanner(System.in);
System.out.println("Enter name :");
p.setName(stdin.next());
System.out.println("Enter gender :");
p.setGender(stdin.next());
System.out.println("Enter age :");
p.setAge(stdin.nextInt());
personList.add(p);
System.out.println("Do you want to add more ?(Y/N)");
if(stdin.next().equalsIgnoreCase("N")) {
break;
}
}
Collections.sort(personList);
System.out.println("The oldest person is " + personList.get(0).getName());