how to add bunch of data into linked list - java

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 + "]";
}
}

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]]

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();

Java arrayList comparison

Could anybody tell me how to list some data in an arrayList according to the integer value that each component of the ArrayList has? This is my main class
import java.util.Scanner;
import java.io.*;
import java.util.Collections;
import java.util.ArrayList;
public class StudentDriver {
public static void main(String[] args) throws IOException {
Scanner scan, urlScan, fileScan;
String url, file;
int count = 0;
scan = new Scanner(System.in);
System.out.println("Enter the name of the file");
fileScan = new Scanner(new File("Data.csv"));
ArrayList<Student> studentList = new ArrayList<Student>();
while(fileScan.hasNext()){
url = fileScan.nextLine();
urlScan = new Scanner(url);
urlScan.useDelimiter(",");
count++;
while(urlScan.hasNext()){
String name = urlScan.next();
String last = urlScan.next();
int score = urlScan.nextInt();
Student e = new Student(name,last, score);
studentList.add(e);
}
}
System.out.println("The file has data for" +count+ "instances");
int option;
do{
System.out.println("********");
System.out.println("Options:");
System.out.println("********\n1. List \n2. Add Student \n3.Delete Student \n4. Exit \n******** ");
System.out.print("Select option: ");
option = scan.nextInt();
if(option == 1){
int index = 0;
while(index<studentList.size()){
System.out.println(studentList.get(index));
index++;
}
}
else if(option == 2){
System.out.print("Enter the name of the student: ");
String newName = scan.next();
System.out.print("Enter the last name of the student: ");
String newLastName = scan.next();
System.out.print("Enter the exam score of the student: ");
int newScore = scan.nextInt();
Student b = new Student(newName, newLastName, newScore);
studentList.add(b);}
else if(option == 3){
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
location = studentList.indexOf(remove1);
studentList.remove(location);
}
}while(option!=4 && option <4);
}//main
}//class
And this is the other class
public class Student implements Comparable<Student>{
String firstName, lastName;
int score;
public Student(String firstName, String lastName, int score){
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString(){
return firstName + " " + lastName + ", exam score is "+ score;
}
#Override
public int compareTo(Student c) {
return score-c.getScore();
}
}
As you can see, up to now I have created the class where my compare method is but I have difficulties on using it. Also I have had difficulties on deleting one of the Array List parts by just writing the name and last name of the student. If somebody would help me, I would be very thankful.
well you can change your compareTo method as
public int compareTo(Student another)
{
if (this.score > another.score)
return -1;
if (this.score < another.score)
return 1;
else
return 0;
}
this should show it as decreasing order you can change the operator
than use whereever you want to sort it
Collections.sort(studentList)
Also if you don't want to use Collections.sort() method I can show you how you can write it with for loop under add option
Student newStd = new Student(name, last, score);
for(int i=0;studentList.size()>i;i++)
{
int size = studentList.size();
if(newStd.compareToCustom(studentList.get(i))>0)
{
studentList.add(i, newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(size-1))<0)
{
studentList.add(studentList.size(), newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(i))==0)
{
studentList.add(i++, newStd);
break;
}
}
for the remove part you can use
else if ( option == 3)
{
System.out.print("Enter the first name of student will be deleted: ");
String removeName = scan.next();
System.out.print("Enter the last name of student will be deleted: ");
String removeLastName = scan.next();
for ( int i = 0; i < studentList.size(); i++)
{
Student deleted = studentList.get(i);
if ( deleted.getFirstName().toLowerCase().equals(removeName.toLowerCase()) && deleted.getLastName().toLowerCase().equals(removeLastName.toLowerCase()))
{
studentList.remove(i);
System.out.println("The student has been deleted.");
break;
}
else
{
System.out.println("This student is not found");
break;
}
}
}
Basically what you want is an ordered collection. As #duffymo has stated, think about a creating a custom Comparator using your score.
There is plenty of info here
In terms of deleting students from the list.
The studentList is a list containing Student objects.
This means that the follow code:
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
Tries to find the index of a Student given the first name. This will return -1 as you're searching for a String and not a Student object.
Instead you have to iterate through your studentList and compare the first and last name of each Student element with the values of remove and remove1.
for(Student student : studentList) {
if(student.getFirstName.equals(remove) && student.getLastName.equals(remove1)) {
// remove the student.
}
}
Also you could consider giving each Student an ID as an unique identifier.
try this to sort studentList
Collections.sort(studentList, new Comparator<Student>()
{
#Override
public int compare(Student x, Student y)
{
if(x.score >= y.score)
return 1;
else
return -1;
}
});

java user input for Array - split by space

All,
Below code is working fine with the ArrayList. could you please help me on how to get user input for name gender and amountSpent (array size [4]), then split it by spaces so that it will have String, String and double.
Also, How to display the result of only the customer who has higher amount Spent then the other Customers.
thank you in advance!
Regards,
Viku
import java.util.Comparator;
public class Customer implements Comparable <Customer>{
public String name,gender;
public double amountSpent;
public Customer(String name, String gender, double amountSpent) {
super();
this.name = name;
this.gender = gender;
this.amountSpent = amountSpent;
}
public String getCustomername() {
return name;
}
public void setCoustomername(String name) {
this.name = name;
}
public String getgender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getamountSpent() {
return amountSpent;
}
public void setamountSpent(double amountSpent) {
this.amountSpent = amountSpent;
}
public static Comparator <Customer> CustomerNameComparator = new Comparator<Customer>() {
public int compare(Customer c1, Customer c2) {
String custName1 = c1.getCustomername().toUpperCase();
String custName2 = c2.getCustomername().toUpperCase();
//ascending order
//return custName1.compareTo(custName2);
//descending order
return custName2.compareTo(custName1);
}
};
public static Comparator <Customer> CustomerAmountSpentComparator = new Comparator<Customer>() {
public int compare(Customer aS1, Customer aS2) {
int custamtspent1 = (int) aS1.getamountSpent();
int custamtSpent2 = (int) aS2.getamountSpent();
//ascending order sort
// return custamtspent1 - custamtSpent2;
//descending order sort
return custamtSpent2 - custamtspent1;
}
};
#Override
public int compareTo(Customer o) {
return 0;
}
#Override
public String toString() {
return " Customer Name : " + name + ", Gender : " + gender + ", Amount Spent : " + amountSpent + "";
}
}
and Main Program:
import java.util.ArrayList;
import java.util.Collections;
public class MainProg {
public static void main(String args[]){
String nL = System.lineSeparator();
try {
ArrayList<Customer> arraylist = new ArrayList<Customer> ();
arraylist.add(new Customer ("Louis","Male", 4567.76));
arraylist.add(new Customer ("Daniela","Female", 7653.67));
arraylist.add(new Customer ("Jenny","Female", 3476.98));
arraylist.add(new Customer ("Arijit","Male", 9876.44));
System.out.println("Customer Name Decending Sort: " + nL);
Collections.sort(arraylist, Customer.CustomerNameComparator);
for (Customer str: arraylist) {
System.out.println(str);
}
System.out.println(nL + "Custmer Amount Spent [Hight to Low] Sorting: " + nL);
Collections.sort(arraylist, Customer.CustomerAmountSpentComparator);
for (Customer str: arraylist){
System.out.println(str);
}
System.out.println(nL + "Highest Amount Spent Custmer Detail: " + nL);
}
catch (Exception e){
System.out.println("Error: " + e);
}
finally {
System.out.println(nL + "Report Completed!");
}
}
}
OPTION 1 (suggested):
If the user is to input the data, why do you need to split it up? Just do as follows:
System.out.println("Name:");
name = scn.nextLine();
System.out.println("Gender:");
gender = scn.nextLine():
System.out.println("Amt:");
amt = scn.nextDouble();
Customer c1 = new Customer (name,gender, amt);
OPTION 2:
Alternatively, if you want user to input everything in one single line (separated by spaces), just do this:
System.out.println("Input name, gender, amt:");
name = scn.next();
gender = scn.next():
amt = scn.next();
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
OPTION 3 (requested by you):
Lastly if you still insist of doing a split by space, and you want to accept the user input in one string separated by spaces:
System.out.println("Input name, gender, amt:");
input = scn.nextLine();
String[] token = input.split(" ");
String name = token[0];
String gender = token[1];
double amt = Double.parseDouble(token[2]);
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
For your first question (if I have understood right), you want to take a user input as string:
Dave Male 123.45
and then parse this into two Strings and a double. Scanner as you mentioned is a good way to start, then try
String[] parts = input.split(" ");
double value = Double.parseDouble(parts[2]);
This will split the input into a String array of size 3 and convert the third element to a double object, that will allow you to create Customers.
For your second question, you can use a simple approach by iterating over all Customers in the ArrayList, and store the current customer with the highest amount. Replacing the customer if you find a bigger spender.
Viku, try moving
arraylist.add(new Customer(name,gender,amountSpent));
to within the
do{
...
arraylist.add(new Customer(name,gender,amountSpent));
} while(choice.equalsIgnoreCase("Yes"));
As the code is now, the arrayList.add is only executed after the loop -> only last entry.

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