Print a specific cell from a string array - java

I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).
I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.
I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".
(Yes, I tested this when I already inserted some data.)
Here's the full code:
package appartamento;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Appartamento {
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyb = new BufferedReader(input);
boolean attiva = true;
do {
System.out.println("what do you want to do?");
System.out.println("1 - check for a person");
System.out.println("2 - Add person");
int choice = Integer.parseInt(keyb.readLine());
Datiutente du[] = new Datiutente[10];
if (choice == 2){
System.out.println("How many people?");
int hm = Integer.parseInt(keyb.readLine());
for (int i=0;i<hm;i++){
du[i] = new Datiutente();
System.out.println("insert name:");
du[i].setName(keyb.readLine());
System.out.println("insert surname");
du[i].setSurname(keyb.readLine());
}
}
if (choice == 1){
System.out.println("which person are you searching?");
int vd = Integer.parseInt(keyb.readLine());
System.out.println("position: " + i);
System.out.println("Name: "+ du[i]);
System.out.println("Surname: " + du[i]);
}
} while (attiva = true);
}
}
and the class "Datiutente":
package appartamento;
public class Datiutente {
private String name;
private String surname;
private String codfis;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSurname(String surname){
this.surname = surname;
}
public String getSurname(){
return surname;
}
}

In every iteration you define the Datiutente du[] = new Datiutente[10];, so du is reset to {null,...,null} and the data saved in the previous iteration are replaced;
Try to define the array before the loop statement.

I found a way here:
You need to insert values on object creation, you can also use hashmaps
hashmap will benefit you more I think.
Code sample to fix your stuff.
class GFG {
public static void main(String args[]){
// Declaring an array of student
Student[] arr;
// Allocating memory for 2 objects
// of type student
arr = new Student[2];
// Initializing the first element
// of the array
arr[0] = new Student(1701289270, "Satyabrata");
// Initializing the second element
// of the array
arr[1] = new Student(1701289219, "Omm Prasad");
// Displaying the student data
System.out.println(
"Student data in student arr 0: ");
arr[0].display();
System.out.println(
"Student data in student arr 1: ");
arr[1].display();
}
}
class Student {
public int id;
public String name;
// Student class constructor
Student(int id, String name)
{
this.id = id;
this.name = name;
}
// display() method to display
// the student data
public void display()
{
System.out.println("Student id is: " + id + " "
+ "and Student name is: "
+ name);
System.out.println();
}
}

Related

(Java) How can I print an object's information when the object is in an ArrayList? [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have an ArrayList in main and I have a class with a constructor inside it and a method to print the data. I add a new object with new information, when called, and adds it to the ArrayList to keep it in one place. What I'm having a hard time is the syntax to print the information. I tried it with a regular array but I need to use ArrayList. I need to be able to get the index of a specific object, and print that object's information. For example, the code below the last couple lines:
import java.util.ArrayList;
import java.util.Scanner;
public class student{
String name;
int age;
int birthYear;
public student(String name, int age, int birthYear){
this.name = name;
this.age = age;
this.birthYear = birthYear;
}
public void printStudentInformation(){
System.out.println(name);
System.out.println(age);
System.out.println(birthYear);
}
}
public class Main{
public static void main(String[] args){
ArrayList listOfObj = new ArrayList();
ArrayList names = new ArrayList();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++){
System.out.println("New Student Information:"); // Three student's information will be saved
String name = sc.nextLine();
int age = sc.nextInt();
int birthYear = sc.nextInt();
student someStudent = new student(name, age, birthYear);
listOfObj.add(someStudent);
names.add(name);
}
System.out.println("What student's information do you wish to view?");
for(int i = 0; i < names.size(); i++){
System.out.println((i + 1) + ") " + names.get(i)); // Prints all students starting from 1
}
int chosenStudent = sc.nextInt(); // Choose a number that correlates to a student
// Should print out chosen student's object information
listOfObj.get(chosenStudent).printStudentInformation(); // This is incorrect, but I would think the syntax would be similar?
}
}
Any help or clarification is greatly appreciated.
You need to change your definition of listOfObj from:
ArrayList listOfObj = new ArrayList();
to:
ArrayList<student> listOfObj = new ArrayList<>();
The first will will create a ArrayList of Object class objects.
The second will create a ArrayList of student class objects.
Few more problems in your code:
Since you are reading name using nextLine, you may need to skip a new line after reading the birth year like:
...
int birthYear = sc.nextInt();
sc.nextLine(); // Otherwise in the next loop iteration, it will skip reading input and throw some exception
...
You select an option for the student to display, but that option is 1 indexed and ArrayList stores 0 indexed, so you should change the line to sc.nextInt() - 1:
int chosenStudent = sc.nextInt() - 1; // Choose a number that correlates to a student
Scanner may throw exception in case you enter, for example, a string instead of an int. So make sure you are handling exceptions properly using try-catch blocks.
You change the ArrayList defination and add toString() in your studen
class.
And to print all the student object insted of using for loop use just
one sop.
EX:-
import java.util.*;
class Student {
private String name;
private int age;
private int birthYear;
public Student() {
super();
}
public Student(String name, int age, int birthYear) {
super();
this.name = name;
this.age = age;
this.birthYear = birthYear;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
#Override
public String toString() {
return "Student [age=" + age + ", birthYear=" + birthYear + ", name=" + name + "]";
}
}
public class DemoArrayList {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
scan.nextLine();
String name = scan.nextLine();
int age = scan.nextInt();
int birthYear = scan.nextInt();
list.add(new Student(name, age, birthYear));
}
System.out.println(list);
}
}
O/P:-
2
joy
10
2003
jay
20
2005
[Student [age=10, birthYear=2003, name=joy], Student [age=20, birthYear=2005, name=jay]]

how to add bunch of data into linked list

Basically, I just tried to learn linked lists but I can't seem to understand how to insert a bunch of data from different variables into it. Does it work as an array/ ArrayList? Before we end the loop we are supposed to store the data right, but how??
Let say I have variables ( name, age, phonenum).
'''
char stop='Y';
while(stop!='N'){
System.out.println("\nEnter your name : ");
int name= input.nextLine();
System.out.println("\nEnter your age: ");
int age= input.nextInt();
System.out.println("\nEnter your phone number: ");
int phonenum= input.nextLine();
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
stop = sc.nextLine().charAt(0);
}
'''
First, change your code to use appropriate types. Name and phone should be of type String, not int.
Define a class to hold your fields. Records are an easy way to do that.
record Person ( String name , int age , String phone ) {}
Declare your list to hold objects of that class.
List< Person > list = new LinkedList<>() ;
Instantiate some Person objects, and add to list.
list.add( New Person( "Alice" , 29 , "477.555.1234" ) ) ;
In the line above, I hard-coded some example data. In your own code, you will be passing to the constructor the variables you populated by interacting with the user.
list.add( New Person( name , age , phonenum ) ) ;
You can create an object which has name, age and phenomenon then create an insert method which you call in your while loop.
In psuedo code it would look something like this:
public class Data {
String name;
int age;
int phenomenon;
//constructor
//getters & setters
}
This class above will hold contain the user input. You can gather all the user input and store it in an array and perform the insert with array of data instead of inserting one object at a time
public void InsertData(LinkedList<Data> list, Arraylist<Data> input) {
for(Data d: input){
list.add(d);
}
}
You can read up on linkedlists a bit more here to understand how exactly linkedlists work and implement your own from scratch: https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/
Try this
Possibility : 1
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<Object> list = new LinkedList<Object>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(name);
list.add(age);
list.add(phonenum);
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
possibility : 2
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<User> list = new LinkedList<User>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(new User(name, age, phonenum));
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
class User {
private String name;
private int age;
private long phonenum;
public User() {
}
public User(String name, int age, long phonenum) {
this.name = name;
this.age = age;
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhonenum() {
return phonenum;
}
public void setPhonenum(long phonenum) {
this.phonenum = phonenum;
}
#Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", phonenum=" + phonenum + "]";
}
}

Need help making ArrayList

I am trying to create an ArrayList using at least six Person objects that will contain user inputted name and age resulting in information being printed out in alphabetical order.
Array list that contains person:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Categorization
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
System.out.println("Please enter a name " + name); // Can't return values
String nameEntry = input.toString();
System.out.println("Please enter an age " + age);
int ageEntry = input.nextInt();
}
}
I am unfamiliar with creating classes and feel like this is where most of my errors occur.
class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
Tried to return name and age but they are not going back to the Public Class
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
}
You can try this:
public class Categorization {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
List<Person> people = new ArrayList<Person>();
for(int i=1; i<=6; i++) {
System.out.print("Please enter name for person " + i + " : ");
String nameEntry = input.next();
System.out.print("Please enter an age for person " + i + " : ");
int ageEntry = input.nextInt();
Person obj = new Person(nameEntry, ageEntry);
people.add(obj);
}
System.out.println("List of entries you entered: ");
for(Person obj: people) {
System.out.println("Name: " + obj.getName() + " " + "Age: " + obj.getAge());
}
}
}
Output:
You need to create a Person object using new keyword to store respective values and then finally add it to the people list.

display an entire arraylist in java

I'm still pretty new to java. Am trying to make a program that basically adds contacts to an array list. I have figured everything out as far as creating a new object and setting the name/number. As far as I can tell it's adding it to the array, however I'm not sure how I can display the array? I want to add a snippet of code that would display the array list after you add each contact.
Here is my contact class, not sure if I need the PhoneBook method or not for the array....
public class Contact {
String first; //first name
String last; //last name
String phone; //phone number
String PhoneBook; //array list???
public void PhoneBook(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public void setFirst(String first) {
this.first = first;
}
public void setLast(String last) {
this.last = last;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Contact makeCopy() {
Contact Contact = new Contact();
Contact.first = this.first;
Contact.last = this.last;
Contact.phone = this.phone;
return Contact;
} //end makeCopy
} //end class Computer
Here is my driver class...
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
Contact Contact = new Contact(); //make default Contact
Contact newContact;
String first; //first name
String last; //last name
String phone; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
Scanner scan = new Scanner(System.in);
Contact.setFirst("Default");
Contact.setLast("Default");
Contact.setPhone("Default");
while (add) {
System.out.println("Would you like to create a new contact? (Y/N)");
input = scan.nextLine();
if (input.equals("Y") || input.equals("y")) {
newContact = Contact.makeCopy();
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
phone = scan.nextLine();
ArrayList < Contact > PhoneBook = new ArrayList();
newContact.setFirst(first);
newContact.setLast(last);
newContact.setPhone(phone);
PhoneBook.add(newContact);
} else {
add = false;
System.out.println("Goodbye!");
break;
}
}
} //end main
} //end Class ComputerDriver
If just for printing, override the toString method of your Contact class, which will be like:
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
Then, in your main method, print all the contacts by doing:
for (Contact c : phoneBook) {
System.out.println(c);
}
Also, you should create the phoneBook, which is an ArrayList outside of your loop.
Your Contact class should be defined as:
public class Contact {
private String first; // first name
private String last; // last name
private String phone; // phone number
public Contact(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String getPhone() {
return phone;
}
public Contact makeCopy() {
return new Contact(first, last, phone);
}
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
}
And your main method should be:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Contact> phoneBook = new ArrayList<>();
while (true) {
System.out.println("Would you like to create a new contact? (Y/N)");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Y")) {
System.out.println("Enter the contact's first name: ");
String first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
String last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
String phone = scan.nextLine();
Contact contact = new Contact(first, last, phone);
phoneBook.add(contact);
for (Contact c : phoneBook) {
System.out.println(c);
}
} else {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
The compiler will give warning, most likely because of this:
String PhoneBook;
when you know that you also have
public void PhoneBook(String f, String l, String p)
and even more another PhoneBook
ArrayList < Contact > PhoneBook = new ArrayList();
try to use another variable name and function name to be safe and make sure they are different especially for
String PhoneBook;
public void PhoneBook(String f, String l, String p)
since they are under same class.
In terms of data structure, you have a wrong concept here. first is, this:
ArrayList < Contact > PhoneBook = new ArrayList();
should be outside the while loop so for whole your application, you will not replace your phone book after looping. to print them, later just use
for(int i = 0; i < phoneBook.size(); i++)
your printing
You just override toString() method of your Contact class, and in main() method, directly call your ArrayList's toString().
Here is my example:
package somepackage;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Inner> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Inner in = new Inner("name" + i, "address" + i);
list.add(in);
}
System.out.println(list.toString());
}
private static class Inner {
private String name;
private String address;
Inner(String name, String address) {
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "name:" + name + ", " + "address: " + address + "\n";
}
}
}
Screen outputs:
[name:name0, address: address0
, name:name1, address: address1
, name:name2, address: address2
, name:name3, address: address3
, name:name4, address: address4
, name:name5, address: address5
, name:name6, address: address6
, name:name7, address: address7
, name:name8, address: address8
, name:name9, address: address9
]
Ok, figured it out thanks to your guys help! I changed the if statement so you can now add a new contact, display the phone book, or quit. I also added phone number validation! Here is the updated code if anyone cares!
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
String first; //first name
String last; //last name
String phone = ""; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
boolean phoneValid; //boolean to validate phone number
Scanner scan = new Scanner(System.in);
ArrayList < Contact > PhoneBook = new ArrayList < > ();
while (add) {
phoneValid = false;
System.out.println("Type (N) to add a new contact, (D) to display your phonebook, or (Q) to quit!");
input = scan.nextLine();
if (input.equalsIgnoreCase("N")) {
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
while (!phoneValid) {
System.out.println("Enter the contact's phone number: XXX-XXX-XXXX");
phone = scan.nextLine();
if (phone.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
phoneValid = true;
break;
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
Contact contact = new Contact(first, last, phone);
PhoneBook.add(contact);
} else if (input.equalsIgnoreCase("Q")) {
add = false;
System.out.println("Goodbye!");
break;
} else if (input.equalsIgnoreCase("D")) {
for (Contact c: PhoneBook) {
System.out.println(c);
}
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
} //end main
} //end Class ComputerDriver
It sounds like you need to create some Getters. Most IDE's will do this for you.
For example, in your contact class add this:
public String getFirst(){ return first; }
Then do that for all of the items you want. When you want to print them out, set up a for each loop in your driver class like this:
for(Contact contact : PhoneBook){
System.out.println("Contact details: " + contact.getFirst() + " " + contact.getLast() + ", Phone #: " + contact.getPhoneNumber());
}
Alternatively, you could also create a method in you contacts class that takes the println contents from above and spits it out. For example:
public void printContactDetails(){ System.out.println("...");}
then in your for each loop call: contact.printContactDetails();

Callling method from another class + sorting

I am working on a program where I have to call a method that prompts the user to enter data from another class. This program should print the name, age, address, and gender of customers. However, I am having problem to call a method for inputting each customer information.
Also, I have to create a method that sort the ages of customers in ascending order. So the program prints out all info based on the order of age from the (youngest customer) to the (oldest one). I am not sure how to create a method that will only sort the ages of customers without sorting the name, address, and gender. I would really appreciate any feedback or comments!
This is what I have so far.
import java.util.Scanner;
public class Customer1 {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int x;
System.out.print("Total number of customers: ");
x = input.nextInt();
Customer [] person = new Customer[x];
System.out.println("Name" + " " + "Age"+ " " + "Address" + " " + "Gender");
for(int i = 0; i < person.length; i++){
System.out.println(person.toString());
}
}
}
class Customer{
String name;
int age;
String address;
String gender;
public Customer(String newName, int newAge, String newAddress, String newGender){
name = newName;
age = newAge;
address = newAddress;
gender = newGender;
}
public void data(Customer [] person){
Scanner input = new Scanner(System.in);
for(int i = 0; i < person.length; i++){
System.out.print("Name: ");
name= input.toString();
System.out.print("Age: ");
age = input.nextInt();
System.out.print("Address: ");
address= input.toString();
System.out.print("Gender: ");
gender = input.toString();
}
}
/*This is the "uncompleted" method that I tried to create in order to sort the ages of customers.
But I don't know how to use it in order to sort only the ages*/
public void sort(Customer [] person){
double temp;
for(int a = 0; a < (person.length - 1); a++){
for( int b = (a + 1); b < person.length; b++){
if(person[a] > person[b]){
temp = person[a];
person[a] = person[b];
person[b] = temp;
}
}
}
}
public String toString(){
String result;
result = name + " " + age + " " + address + " " + gender;
return result;
}
}
I recommend you to rethink a little bit your code and take a look at the following tips
Using Comparator or Comparable interfaces
These interfaces helps you out with the sorting of your collections, lists and etc, i.e, the Comparator interface allows you to impose ordering to your collection with a hand from Collections.sort and Arrays.sort operations.
You must define the implementation of you Comparator, based on you target class(Person), then define the ordering by any field you want:
class PersonSort implements Comparator<Person>{
#Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}}
Then you are allowed to force its ordering via Arrays.sort(T[], Comparator):
Arrays.sort(yourArray, new PersonSort());
I also recommend you to take a look at Oracle's Collection Framework Tutorial. You will find information over ordering, implementations and etc.
Try out the below code which might solve this question .. I have included the methods suggested in the previous replies and created this program ..
import java.util.Scanner;
public class ReadSortCustomerData {
public static void main(String [] args) {
int numberOfCustomers;
Scanner input = new Scanner(System.in);
System.out.print("Enter the total number of customers: ");
numberOfCustomers = input.nextInt();
CustomerData [] customer = new CustomerData[numberOfCustomers];
for(int countCustomer=0 ; countCustomer < numberOfCustomers; countCustomer++) {
System.out.println("Enter the name of the"+(countCustomer+1)+"customer");
customer[countCustomer].setName(input.next());
System.out.println("Enter the age of the"+(countCustomer+1)+"customer");
customer[countCustomer].setAge(input.nextInt());
System.out.println("Enter the gender of the"+(countCustomer+1)+"customer");
customer[countCustomer].setGender(input.next());
System.out.println("Enter the address of the"+(countCustomer+1)+"customer");
customer[countCustomer].setGender(input.next());
}
}
public CustomerData[] sortCustomerData(CustomerData[] customers) {
for (int i=0;i<customers.length;i++) {
for(int j=i+1;j<customers.length;j++) {
if(ageCompare(customers[i], customers[j])==1) {
CustomerData tempCustomer = new CustomerData();
tempCustomer = customers[i];
customers[i] = customers[j];
customers[j] = tempCustomer;
}
}
}
return customers;
}
public int ageCompare(CustomerData a, CustomerData b)
{
return a.getAge() < b.getAge() ? -1 : a.getAge() == b.getAge() ? 0 : 1;
}
}
import java.util.Comparator;
import java.util.Scanner;
public class CustomerData {
private String name;
private int age;
private String address;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
This might need some tweaking during the run time but it should give you a good start.
1. Getting the data that you require
Currently in your Customer1 class you're accepting an x amount of customers provided from user input. Following which you create an array for x Customer objects. You do not currently populate the array with any data.
Customer[] person = new Customer[x];
After this line you could then do a for loop with the following:
String name;
int age;
String address;
String gender;
for( int i = 0; i < person.length; i++ )
{
System.out.print("Name: ");
name = input.next();
System.out.print("Age: ");
age = input.nextInt();
System.out.print("Address: ");
address= input.next();
System.out.print("Gender: ");
gender = input.next();
person[i] = new Customer( name, age, address, gender );
}
A cavaet must be observed in your code, you've put input.toString(). This will give you a string representation of your scanner, not the input. input.next() will give you next input as a string.
2.Sorting
I would advise looking at the comparator documentation. Have a comparator object that implements comparator with Customer as the type parameter. Override the compare to check against each Customer object's age.
Example would be:
class CustomerComparator implements Comparator<Customer>
{
#Override
public int compare(Customer a, Customer b)
{
return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
}
}
You should look into making the variables name, age, address gender private and using getX() methods (getters/setters).

Categories