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.
Related
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 + "]";
}
}
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.
I have another small class containing the main method that display the
invoice, but the toString method here is only displaying the last item
entered, not the three itemnames,quantities, prices and totalPrice.
I have doubts about addItemLine and toString.
Can someone see what I am missing here?
I was enable to past the lineItem class code.
import java.util.ArrayList;
import java.util.Scanner;
public class Transaction {
private ArrayList<lineItem> lineItems;
private int customerID;
private String customerName;
public Transaction (int customerID, String customerName){
this.customerID= customerID;
this.customerName= customerName;
this.lineItems= new ArrayList<>();
}
public int getcustomerID(){
return customerID;
}
public void setcustomerID(int customerID){
this.customerID = customerID;
}
public String getcustomerName(){
return customerName;
}
public void setcustomerName(String customerName){
this.customerName = customerName;
}
public ArrayList addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
}
return this.lineItems;
}
public void updateItem(String item, int quant, double pri){
lineItem l= new lineItem(item, quant, pri);
int m=0;
m= l.getQuantity();
m=m+quant;
double tot=0;
}
public double getTotalPrice(){
double totalPrice = 0;
for (int i =0;i<2; i++){
lineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem( String s, int d, double k){
lineItem o= new lineItem(s,d,k);
for (int i =0;i<2; i++){
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toString(lineItem lin) {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (int i=0; i<2;i++){
b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "
"
+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
return a + b;
}
TransactionTesting:
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
String m=""; int g=0; double r=0; int id=0; String name="";
Scanner mykey= new Scanner(System.in);
System.out.println("enter customer name:");
name= mykey.nextLine();
System.out.println("enter customer ID:");
id=mykey.nextInt();
Transaction mytrans= new Transaction(id, name);
lineItem line= new lineItem(m,g,r);
mytrans.addItemLine(line);
System.out.println(mytrans.toString(line));
}
}
Change your toString() method like this:
public String toString() {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (lineItem item : this.lineItems)
b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + " "
+ "#" + item.getPrice() + " "+ "\t" + "$" + item.getPrice());
return a + b;
}
and from your test class call this method as the following:
System.out.println(mytrans.toString());
You don't need any argument in order to print your entire list.
Try to refactor your code a bit. It works, but it can be written better and better ;)
1) The call
System.out.println(mytrans.toString(line));
is printing out the single lineitem that is passed to it. What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn.
In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance.
2) There is a similar confusion in Transacton.addItemLine(). It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems. It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; addItemLine doesn't need it.
3) Incidentally:
for (int i=0; i<2;i++){ }
loops twice, not three times. I trust you would have caught that in testing.
4) There is also a line of code near the end of addItemLine that doesn't actually do anything! Maybe you can spot that one on your own.
There are some other issues but those are the ones that leapt out at me.
Just a quick non-tested solution that may work. Something is copied from your code, something is changed because your code was wrong.
// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;
public void addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
// This doesn't have to return anything, it just adds to the list
}
// No parameteres, this should build the string for the current object
public String toString() {
// String concatenation is not the best idea, StringBuilder is better
StringBuilder sb = new StringBuilder();
// If you want to print all of them then you need to iterate over the list
for (lineItem item : lineItems){
sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
for (int i=0; i<2;i++){
// Copied from your code
sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
sb.append("\n);
}
return sb.toString();
}
It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view.
Here's a test run of your code, after I made some changes.
Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89
Customer ID: 123
Customer Name: Gilbert
Spinach Qty 5 #0.89 $4.45
Enter item name: Corn
Enter quantity: 12
Enter unit price: .29
Customer ID: 123
Customer Name: Gilbert
Corn Qty 12 #0.29 $3.4799999999999995
Enter item name:
First, let's look at your Java objects. The first Java object which you didn't include, is LineItem. Note that Java class names start with a capital letter.
package com.ggl.transaction;
public class LineItem {
private String itemName;
private int quantity;
private double price;
public LineItem(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTotalPrice() {
return price * quantity;
}
}
A Java object consists of class fields, and getters and setters for the fields.
Next, here's your Transaction class.
package com.ggl.transaction;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private List<LineItem> lineItems;
private int customerID;
private String customerName;
public Transaction(int customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
this.lineItems = new ArrayList<>();
}
public int getcustomerID() {
return customerID;
}
public void setcustomerID(int customerID) {
this.customerID = customerID;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public void addItemLine(LineItem line) {
this.lineItems.add(line);
}
public void updateItem(String item, int quant, double pri) {
LineItem l = new LineItem(item, quant, pri);
int m = 0;
m = l.getQuantity();
m = m + quant;
l.setQuantity(m);
}
public double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < 2; i++) {
LineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem(String s, int d, double k) {
LineItem o = new LineItem(s, d, k);
for (int i = 0; i < 2; i++) {
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s = (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toItemString(LineItem lin) {
String b = "";
String a = ("Customer ID: " + this.getcustomerID() + "\n"
+ "Customer Name: " + this.getcustomerName());
for (int i = 0; i < 2; i++) {
b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
+ " " + "#" + lin.getPrice() + " " + "\t" + "$"
+ lin.getTotalPrice() + "\n");
}
return a + b;
}
}
I simplified your addItemLine class. Code that receives input using the Scanner class belongs in your TransactionTesting class.
I renamed your toString method to toItemString. toString is a method of the Object class. Since your method has a parameter, I renamed it to lessen any confusion.
Finally, here's your TransactionTesting class. I fixed it up so it would work. You can specify any number of line items. To stop processing, just enter a blank item name.
package com.ggl.transaction;
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
Scanner mykey = new Scanner(System.in);
System.out.print("Enter customer name: ");
String name = mykey.nextLine().trim();
System.out.print("Enter customer ID: ");
int id = Integer.valueOf(mykey.nextLine().trim());
Transaction mytrans = new Transaction(id, name);
boolean processing = true;
while (processing) {
System.out.print("Enter item name: ");
String k = mykey.nextLine().trim();
if (k.equals("")) {
processing = false;
} else {
System.out.print("Enter quantity: ");
int m = Integer.valueOf(mykey.nextLine().trim());
System.out.print("Enter unit price: ");
double d = Double.valueOf(mykey.nextLine().trim());
LineItem lineItem = new LineItem(k, m, d);
mytrans.addItemLine(lineItem);
System.out.println("\n" + mytrans.toItemString(lineItem));
}
}
mykey.close();
}
}
Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting).
Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances.
Then in the test code you print the original lineItem, which is not even in the list.
The method itself iterates on nothing, just creates twice the same string "b".
I suggest you to look at some tutorials on arrays and for loops.
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).
I'm a college student doing a Java homework. I've created this program that allows user to enter a job information.
The problem is that my program doesn't return information entered.
I look at my program for a while, but I know it's something simple I'm missing.
public class Employee
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate;
public void setEmployeeNumber(String e)
{
if (isValidEmpNum(e))
{
employeeNumber = e;
}
else
{
employeeNumber = "";
}
}
public Employee(String name, String e, String hireDate, double payRate, int shift)
{
this.name = name;
this.setEmployeeNumber(e);
this.hireDate = hireDate;
this.payRate = payRate;
this.shift = shift;
}
public Employee()
{
name = "";
employeeNumber = "";
hireDate = "";
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public double getpayRate()
{
return payRate;
}
public void setshift(int shift)
{
this.shift = shift;
}
public int getshift()
{
return shift;
}
public void setName(String name)
{
this.name = name;
}
public void setHireDate(String hireDate)
{
this.hireDate = hireDate;
}
public String getName()
{
return name;
}
public String getEmployeeNumber()
{
return employeeNumber;
}
public String getHireDate()
{
return hireDate;
}
private boolean isValidEmpNum(String e)
{
boolean status = true;
if (e.length() != 5)
status = false;
else
{
if ((!Character.isDigit(e.charAt(0))) ||
(!Character.isDigit(e.charAt(1))) ||
(!Character.isDigit(e.charAt(2))) ||
(e.charAt(3) != '-') ||
(!Character.isLetter(e.charAt(4))) ||
(!(e.charAt(4)>= 'A' && e.charAt(4)<= 'M')))
{
status = false;
}
}
return status;
}
public String toString()
{
String str = "Name: " + name + "\nEmployee Number: ";
if (employeeNumber == "")
{
str += "INVALID EMPLOYEE NUMBER";
}
else
{
str += employeeNumber;
}
str += ("\nHire Date: " + hireDate);
return str;
}
}
I declared this in another class.
import javax.swing.JOptionPane;
public class ProductionWorkerDemo extends Employee
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
ProductionWorkerDemo pw = new ProductionWorkerDemo();
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You need to use an appropiate constructor or the set* methods to set the fields on the object. Currently, all of them are empty, thus the get* methods return either nothing or default values.
Also, you shouldn't extend Employee with the class containing the main method, just use the Employee class directly (the idea behind inherting from a class is to extend it, in your case you just need it as an object so save data, so don't derive from it but use it):
import javax.swing.JOptionPane;
public class ProductionWorkerDemo
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
Employee pw = new Employee(/*provide arguments here*/);
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You are setting the employee information on local variables only. You are not passing them to the ProductionWorkerDemo nor it's super class Employee.
You don't need to extend the Employee with the ProductionWorkerDemo as the ProductionWorkerDemo is not an Employee. You can just remove the extends Employee text.
You're not passing the variables to the Employee. You've created a constructor in the Employee class that takes them all so you can use it
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
Now you'll notice that you haven't asked for the shift.
First you need to add the constructor you the Demo Class:
public class ProductionWorkerDemo extends Employee{
public ProductionWorkerDemo(String name, String e, String hireDate, double payRate, nt shift){
{
super(name, e, hireDate, payRate, shift);
}
}
Then in your class you need to instantiate:
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,
employeeNumber,
hireDate,
payRate,
shift);
You are declaring variables called name, employeenumber, etc in your main method. When you try to use them, it's going to use those, not your class variables.
why don't you try making a new ProductionWorkerDemo based on the constructor you defined in Employee class?
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,employeeNumber,hireDate,payRate,shift);
And also, your payRate is being assigned twice, you should change the first one to shift, and use Integer.parseInt
You have local variables in main() whose values you are setting. You then create a ProductionWorkerDemo object, who has instance variables with the same names, but are all initially empty, due to the constructor setting them that way.
You never pass your local variables in to your ProductionWorkerDemo object, so when you call the getters they return the empty values.
I fix the problem with my program, thanks for the help everyone.
I was not passing the variables to the Employee.
I add this statement to ProductionWorkerDemo class.
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
P.S. You can close this thread.