I am working on my final for school, and am running into a bit of an issue.
I have created different sorts for the user to sort the information, but I have been getting different errors.
The main one being "The method sort(List, Comparator) in the type Collections is not applicable for the arguments (ApplicationList, ApplicationList.AgeComparator)".
I do not know what this means, or how to fix it.
The code is as follows:
ApplicationList.Java;
import java.util.*;
public class ApplicationList implements Comparable<ApplicationList>
{
/**
* variables within the queue class
*/
private int maxSize;
private String[] queArray;
private int front;
private int rear;
private int nItems;
/**
* This is the constructor
*/
public ApplicationList(int size) {
maxSize = size;
queArray = new String[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
/**
* Adds to the bottom of the queue, and determines if the queue is full
*/
public void enqueue(String j) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (rear == maxSize - 1)
rear = front - 1;
queArray[rear + 1]=j;
rear++;
nItems++;
}
}
/**
* dequeues items from the top of the queue
*/
public String dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
} else {
String j = queArray[front];
front++;
if (front == maxSize)
front = 0;
nItems--;
return j;
}
}
/**
* peeks at the front of the queue
*/
public String peekFront() {
return queArray[front];
}
/**
* determines if the queue is empty
*/
public boolean isEmpty() {
return (nItems == 0);
}
/**
* Determines if the queue is full
*/
public boolean isFull() {
return (nItems == maxSize);
}
/**
* determines size of queue
*/
public int size() {
return nItems;
}
public void display()
{
for (int i = 0; i< nItems; i++)
System.out.println(queArray[(front+i) % maxSize]);
System.out.println(" ");
}
private String lastName;
private String firstName;
private int age;
private String email;
private String education;
private String experience;
public ApplicationList(String lastName, String firstName, int age, String email, String education, String experience)
{
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
this.email = email;
this.education = education;
this.experience = experience;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String toString() {
return "Applicant: Last Name: " + lastName + " ||| " +"First Name: " + firstName +" ||| " + " Email: " + email +" ||| " + " Age: " + age +" ||| " +
" Education: " + education +" ||| " + " Experience: " + experience;
}
static List<String> definedOrder = Arrays.asList("4+ years","2 years","Diploma","GED","NA");
static Comparator<ApplicationList> EducationComparator= new Comparator<ApplicationList>() {
public int compare(ApplicationList e1, ApplicationList e2) {
return Integer.valueOf(definedOrder.indexOf(e1.getEducation())).compareTo(Integer.valueOf(e2.getEducation()));
}
};
static class AgeComparator implements Comparator<ApplicationList> {
public int compare(ApplicationList p1, ApplicationList p2) {
int age1 = p1.getAge();
int age2 = p2.getAge();
if (age1 == age2)
return 0;
else if (age1 > age2)
return 1;
else
return -1;
}
}
public int compareTo(ApplicationList n) {
return getLastName().compareTo(n.getLastName());
}
}
Here is the driver, which is the one that is causing the problem:
ApplicationDriver.Java;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class ApplicationDriver
{
public static <T> void main(String[] args) throws IOException {
ApplicationList Applicants = new ApplicationList(5);
ApplicationList sSmith = new ApplicationList("Smith", "Steve", 34, "SSmith#work.email", "GED", "Did a review on other games, hoping to review yours as well." );
ApplicationList jRosen = new ApplicationList("Rosen", "Jane", 23, "RosenWall#zmail.com", "4+ years", "Game reviewing was somthing I've always wanted to try." );
ApplicationList hAbhul = new ApplicationList("Abhul", "Habib", 19, "SwimminIndian#LookIn.org", "NA", "I like playing games, and feel like I have good insight." );
ApplicationList aJones = new ApplicationList("Jones", "Abigail",27, "Jonsin4Love#zmail.com", "2 years", "I went to school for journalism, and think that I can write a fair and honest review of your games." );
ApplicationList gInsider = new ApplicationList("Insider", "Gaming",0, "Michael#G.Insider.com", "Diploma", "Hi there, I am Michael from Gaming Insider. I see you are an upcoming developer, and want to see what you can do." );
Applicants.enqueue(sSmith.toString());
Applicants.enqueue(jRosen.toString());
Applicants.enqueue(hAbhul.toString());
Applicants.enqueue(aJones.toString());
Applicants.enqueue(gInsider.toString());
boolean success;
while(true) {
System.out.print("Enter the first letter of ");
System.out.print("display, sort, remove: ");
int choice = getChar();
switch(choice) {
case 'd':
Applicants.display();
break;
case 's':
System.out.print("Enter the first letter to sort by ");
System.out.print("name, age, education: ");
int select = getChar();
case 'e':
Collections.sort(Applicants, ApplicationList.EducationComparator);
Applicants.display();
break;
case 'a':
Collections.sort(Applicants, new ApplicationList.AgeComparator());
Applicants.display();
break;
case 'n':
Collections.sort(Applicants);
Applicants.display();
break;
case 'r':
Applicants.dequeue();
Applicants.display();
break;
default:
System.out.println("Invalid Entry, retry\n");
}
}
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
The Collections.sort is where my problems lie. What do I do to go about fixing my issues? If you need any more information, please ask!
Thanks for any and all help you are willing to give, and I apologize if my formatting for the website is horrible, I tried my best with it.
Thank you again for the assistance!
Aaron
You are violating the Single Responsibility Principle.
ApplicationList seems to represent two things:
a list of applicants
an applicant
Those two ideas are very distinct. You should create a class for each of them. To represent a list of applicants, you have a class called ApplicationList, and to represent one individual applicant, make a class called Applicant. Move all the fields and methods related to the applicant to the Applicant class (the age, name, email etc, and the constructor taking these parameters...). And then you can change queArray's type to Applicant[].
Your Collection.sort does not work because ApplicationList does not implement Collection.
Now, you need to implement the Collection interface in order for the ApplicationList to be sorted with Collection.sort. The interface has quite a few methods but they should be easy to implement.
Alternatively, you can just call Arrays.sort and sort the queArray instead.
Related
This question already has answers here:
method in class cannot be applied to given types
(7 answers)
Closed 2 years ago.
I wish to be able to update information about objects entered by a user. I would like the user to enter a book name and user name to take out the book, as well as being able to return it with the same information. The objects have to be inserted into the right place in my sortedarraylists. Each user is assumed to be unique and each book can only be taken out by one user (who can take out up to 3 books).
When I try to compile my code, I get this error message:
java: method issueBook in class Driver cannot be applied to given types;
required: Book,User
found: no arguments
reason: actual and formal argument lists differ in length
This corresponds to issueBook(); in case i of my menu.
I also have User and Book classes that implement Comparable<Book> etc. I tried to omit as much irrelevant code as I could, such as the filereader to scan in new user and book objects. I included the book and user classes in case they need to be looked at (I think they are mostly fine). Please let me know if you need any more details however.
import java.io.*;
import java.util.Scanner;
public class Driver {
static Scanner sc = new Scanner(System.in);
private static void mainMenu() {
System.out.println("------------------------------\n"+
"f: Finish running the program\n" +
"b -Display on the screen the information about all the books in the library\n" +
"u -Display on the screen the information about all the users.\n" +
"i -Update the stored data when a book is issued to a user\n" +
"r -Update the stored data when a user returns a book to the library\n" +
"------------------------------\n" +
"Type a letter and press Enter\n");
}
private static User readNames() throws User.InvalidBookLimitException {
System.out.println("Enter the user's firstname: ");
String firstName = sc.next();
System.out.println("Enter the user's surname: ");
String surName = sc.next();
sc.nextLine(); //TODO check this
return new User(firstName, surName, 0);
}
private static User readUserData(User user) throws User.InvalidBookLimitException {
User u = readNames();
System.out.println("Enter " + user + "'s age, and press Enter");
int numberOfBooks = sc.nextInt();
sc.nextLine();
return new User(u.getFirstName(), u.getSurName(),u.getNumberOfBooks());
}
private static Book readBookName (){
System.out.println("Type in the name of the book");
String bookName = sc.nextLine();
return new Book(bookName);
}
/* public SortedArrayList<User> sortedUsers = new SortedArrayList<>(); public SortedArrayList<Book> sortedBooks = new SortedArrayList<>();*/
//If this part is commented out, I get errors since I can't seem to access the arraylists in the
// main method for the issueBook/returnBook methods.
public void issueBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(true);
/*b.setLoanerNames(user);*/ b.setLoanerNames("John", "Doe");
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()+1);
}
}
}
public void returnBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(false);
b.setLoanerNames(null, null);
break;
} for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()-1);
}
}
}
}
public static <E> void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
//These SortedArrayLists have been derived from the sorted arraylist class
SortedArrayList<User> sortedUsers = new SortedArrayList<>();
SortedArrayList<Book> sortedBooks = new SortedArrayList<>();
mainMenu(); //main menu printing method
char ch = sc.next().charAt(0);
sc.nextLine();
while (ch !='f') //the program ends as desired if f is pressed
{ switch(ch){
case 'b':
System.out.println("Displaying information about all books in the library: ");
/*for (Object item : sortedBooks) {
System.out.println(sortedBooks.toString());
}*/
System.out.println(sortedBooks/*.toString()*/);
break;
case 'u':
System.out.println("Displaying information about all users");
System.out.println(sortedUsers/*.toString()*/);
break;
case 'i':
System.out.println("Enter the loaning out data. ");
System.out.println("Enter the user's first name and surname: ");
readNames();
System.out.println("Enter the name of the book: ");
readBookName();
issueBook();
or maybe if(u1.compareTo(u2) == 0)*/
break;
case 'r':
System.out.println("Please the details of the book to be returned: ");
/*Book b = new Book("test1", "test2", true, "lol","lol2");*/
//this was just a test and didn't work
/*returnBook(b);*/
break;
default:
System.out.println("Invalid input, please enter f, b, i or r");
}
mainMenu();
ch = sc.next().charAt(0);
sc.nextLine();
}
}
}
My sorted arraylist class with a (working) insert method:
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {
//no need for a generic in the insert method as this has been declared in the class
public void insert(E value) {
if (this.size() == 0) {
this.add(value);
return; }
for (int i = 0; i < this.size(); i++) {
int comparison = value.compareTo((E) this.get(i));
if (comparison < 0) {
this.add(i, value);
return; }
if (comparison == 0) {
return; }
}
this.add(value);
}
User class:
import java.io.PrintWriter;
public class User implements Comparable<User> {
private String firstName;
private String surName;
private int numberOfBooks;
public User(){
firstName = "";
surName = "";
numberOfBooks = 0;
}
public class InvalidBookLimitException extends Exception{
public InvalidBookLimitException(){
super("Invalid number of books");
}
}
public User(String name1, String name2, int books) throws InvalidBookLimitException {
this.firstName = name1;
this.surName = name2;
if (books>3) throw new InvalidBookLimitException ();
this.numberOfBooks = books;
}
public String getFirstName() {
return firstName;
}
public String getSurName(){
return surName;
}
public int getNumberOfBooks(){
return numberOfBooks;
}
public boolean borrowMoreBooks(){
return numberOfBooks < 3;
}
public void setNumberOfBooks(int numberOfBooks){
this.numberOfBooks=numberOfBooks;
}
public void setUser(String name1, String name2, int books){
firstName = name1;
surName = name2;
numberOfBooks = books;
}
public boolean userNameTest (User otherUser){
return (firstName.equals(otherUser.firstName) && surName.equals(otherUser.surName));
}
/* public boolean loanAnotherBook(){
return !(numberOfBooks<3);
numberOfBooks++;
}*/
public void printName(PrintWriter f){f.println(firstName+ " " + surName);}
/*
public void setUser(User user) {
if (loanStatus == false){
loanStatus = Driver.readNameInput();
loanStatus = true;
}
}*/
#Override
public String toString(){
return "Name: " + firstName + " " + surName + " | Number of books: " + numberOfBooks;
}
public int compareTo(User u) {
/* int snCmp = surName.compareTo(u.surName);
if (snCmp != 0)
return snCmp;
else{
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp !=0)
return fnCmp;
}*/
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp != 0) return fnCmp;
int snCmp= surName.compareTo(u.surName);
if (snCmp !=0) return snCmp;
else return numberOfBooks -u.numberOfBooks;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
Book class:
public class Book implements Comparable<Book>{
public String bookName;
public String authorName;
public boolean loanStatus;
public String loanerFirstName;
public String loanerSurName;
//if boolean loanStatus == true private string loaner name
public Book(){
bookName = "";
authorName = "";
loanStatus = false;
loanerFirstName = null;
loanerSurName = null;
}
Book(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName) {
this.bookName = book;
this.authorName = author;
this.loanStatus = loanStatus;
this.loanerFirstName = loanerFirstName;
this.loanerSurName = loanerSurName;
}
Book(String book){
this.bookName=book;
}
public String getBookName(){
return bookName;
}
public String getAuthorName(){
return bookName;
}
public boolean getLoanStatus(){
return loanStatus;
}
public String getLoanerFirstName(){
return loanerFirstName;
}
public String getLoanerSurName(){
return loanerSurName;
}
public void setBook(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName){
bookName = book;
authorName = author;
loanStatus = loanStatus;
loanerFirstName = loanerFirstName;
loanerSurName = loanerSurName;
}
public void setBookName(String bookName){
this.bookName=bookName;
}
public void loanStatus(boolean loanStatus){
this.loanStatus=loanStatus;
}
public void setLoanerNames(String loanerFirstName, String loanerSurName){
this.loanerFirstName=loanerFirstName;
this.loanerSurName=loanerSurName;
}
/* public boolean nameTest (User otherUser){
return (loanerFirstName.equals(otherUser.loanerFirstName)&& loanerSurName.equals(otherUser.loanerSurName));
}
*/
public String toString(){
return "Book: " + bookName + " | Author: " + authorName + " | Loan status: " + loanStatus + " | Loaned to: " + loanerFirstName + " " + loanerSurName ;
}
//this may be redundant TODO
/* public void setLoanStatus(User user){
loanStatus = false;
}*/
//This compare method allows new user objects to be compared to ones in the
#Override //sortedArrayList, enabling the insertion method.
public int compareTo(Book b) {
int bnCmp = bookName.compareTo(b.bookName);
if (bnCmp != 0) return bnCmp;
int anCmp= authorName.compareTo(b.authorName);
if (anCmp !=0) return anCmp;
// int lsCmp= loanStatus.(b.loanStatus);
// if (lsCmp !=0) return lsCmp;
int lrfnCmp =loanerFirstName.compareTo(b.loanerFirstName);
if (lrfnCmp !=0) return lrfnCmp;
int lrlnCmp =loanerSurName.compareTo(b.loanerSurName);
if (lrlnCmp !=0) return lrlnCmp;
else return 0;
}
}
User user = readNames();
Book book = readBookName();
issueBook(book, user);
You have to pass the user and book which you have created while calling the issueBook method.
My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0 4590.0 2390.0 2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00 4819.50 2390.00 2629.00
Generally, when implementing equals(), you compare “key” fields whose values don’t change for the entity, and don’t compare “state” fields whose values change from time to time.
You are comparing sharePrice, when I believe you should be comparing symbol.
When you do list.indexOf(temp), what that does, right now, is look for a Stock that is equals to the argument passed to it -- so it looks for a Stock with price zero, not caring about the symbol at all. That's what the code does right now.
Honestly, using indexOf and equals is not really appropriate for this problem. indexOf is really only useful when you have something that's totally equal to the target you're looking for.
The best way to do something like this is
Optional<Stock> foundStock = list.stream().filter(stock -> stock.getName().equals(symbol)).findAny();
if (foundStock.isPresent()) {
// do something with foundStock.get()
} else {
// no found stock
}
indexOf() is a method return the index of the first occurrence of the specified element in the returned list. If the list does not contain this element, value -1 is returned.
More formally, return the lowest index i that meets the following conditions:
if(o==null? get(i)==null :o.equals(get(i))){
return i;
}
return -1;
If there is no such index, return -1.
And you have override the equals method, I guess you just want to focus on the same price Stock?:
#Override
public boolean equals(Object obj){
if (obj instanceof Stock){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}
return false;
}
As my opinion, you have use List<Stock> list so the Object in the list is all Stock. Maybe it could be simplifed:
#Override
public boolean equals(Object obj){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}
I'm made a program that creates an invoice but when it comes numbers in the thousands the output isn't neat and ruins everything. How do I fix this so the program's columns are more aligned with numbers like this? Here is the code I used to create the program. If anyone could help, it would be much appericated.
Here's the one with the main method...
public class InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress=new Address("Sam's Small Appliances", "100 Main
Street", "Anytown", "CA", "98765");
Invoice samsInvoice =new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95),3);
samsInvoice.add(new Product("Hair Dryer", 24.95),1);
samsInvoice.add(new Product("Car Vacuum",19.99),2);
samsInvoice.add(new Product("Nano Parts",100000),1);
samsInvoice.addSimple(new Product("Shipping",5.00));
System.out.println(samsInvoice.format());
}
}
These are the other programs needed for the program to work
import java.util.ArrayList;
public class Invoice
{
public Invoice(Address anAddress)
{
items=new ArrayList<LineItem>();
billingAddress=anAddress;
simpleItems= new ArrayList<SimpleLineItem>();
}
public void addSimple(Product aProduct)
{
SimpleLineItem anItem= new SimpleLineItem(aProduct);
simpleItems.add(anItem);
}
public void add(Product aProduct, int quantity)
{
LineItem anItem=new LineItem(aProduct,quantity);
items.add(anItem);
}
public String format()
{
String r=" I N V O I C E\n\n"+billingAddress.format()+String.format("\n\n%-30s%8s%5s%8s\n","Description", "Price","Qty","Total");
for(LineItem i:items)
{
r=r+i.format()+"\n";
}
for(SimpleLineItem j:simpleItems)
{
r=r+j.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue()
{
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
for(SimpleLineItem j:simpleItems)
{
amountDue = amountDue + j.getPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
private ArrayList<SimpleLineItem> simpleItems;
}
Few more
public class LineItem
{
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice()
{
return theProduct.getPrice() *quantity;
}
public String format()
{
return String.format("%'-30s%'8.2f%'5d%'8.2f", theProduct.getDescription(),theProduct.getPrice(),quantity,getTotalPrice());
}
private int quantity;
private Product theProduct;
}
Another one
public class SimpleLineItem
{
public SimpleLineItem(Product aProduct)
{
theProduct=aProduct;
}
public double getPrice()
{
return theProduct.getPrice();
}
public String format()
{
return String.format("%-30s" +" " + "%8.2f",
theProduct.getDescription(), theProduct.getPrice());
}
private Product theProduct;
}
Two more
public class Product
{
public Product(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
private String description;
private double price;
}
Last one
public class Address
{
public Address(String aName, String aStreet, String aCity, String
aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format()
{
return name + "\n" + street + "\n" + city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
Maybe you can take a look at the javadocs by Oracle on System.out.format and DecimalFormat class
Formatting Numeric Print Output
So basically this happens when you cannot decide the total length of your number column until you print out everything. For this you will need to set the number column's length to the lengthiest number or in your case price length and justify right all the numbers. So you'll need to add all the numbers to an array and loop through them to find the lengthiest number.
i have gotten the assignment to make a phonebook with 3 classes, the driver that runs it all, phonebook,and a person class.
the problem i was having was i couldn't make the Collection.sort(telbook.personen)
get to work as how i have it in my code, what i want to know is what do i have to add or replace to make it sort the arraylist
as i have it now as a function that i can run by myself to check if it did sort, but that didn't work.
driver class:
/**
* Created by ricardo on 2/26/2015.
*/
import java.util.*;
public class Driver {
Phonebook telbook = new Phonebook();
Scanner scan = new Scanner(System.in);
String newLine = System.getProperty("line.separator");
String[] Commands = {"/addperson - add a person to my beautiful program",
"/listpersons - for full list of persons",
"/removeperson - to remove a made person",
"/sortlist - sorts the phonebook (alphabetically)"};
private boolean running;
private boolean startmessage = false;
public static void main(String[] args) {
Driver n = new Driver();
n.run();
}
public void run() {
running = true;
startProgram();
}
public void startProgram() {
while (running) {
if (!startmessage) {
System.out.println("Type /commands for all available commands.");
startmessage = true;
}
String entered = scan.nextLine();
if (entered.equals("/commands")) {
for (int i = 0; i < Commands.length; i++)
System.out.println(Commands[i]);
} else if (entered.equals("/addperson")) {
addPerson();
} else if (entered.equals("/listpersons")) {
listPersons();
} else if (entered.equals("/removeperson")) {
removePerson();
} else if (entered.equals("/sortlist")) {
sortList();
} else {
System.out.println("Command not available. Type /commands for full list of commands");
}
}
}
public void addPerson() {
System.out.println("Fill in your name");
String addname = scan.nextLine();
System.out.println("Fill in your adress");
String addadress = scan.nextLine();
System.out.println("Fill in your city");
String addcity = scan.nextLine();
System.out.println("Fill in your phonenumber");
String addphonenumber = scan.nextLine();
System.out.println("Your data has been saved!");
Person addperson = new Person(addname, addadress, addphonenumber, addcity);
telbook.personen.add(addperson);
//sortList();
}
public void removePerson() {
listPersons();
System.out.println("Insert the ID of the person to be removed");
int ID = Integer.parseInt(scan.nextLine());
if (ID > telbook.personen.size()) {
System.out.println("There is no person with this ID, please select a different ID");
removePerson();
} else {
telbook.personen.remove(ID);
System.out.println("Person with the ID of " + ID + " has been removed");
}
}
public void listPersons() {
int ID = 0;
if (telbook.personen.isEmpty()) {
System.out.println("There is no person added yet. type /addperson to do so");
}
for (int i = 0; i < telbook.personen.size(); i++) {
System.out.println("ID:" + ID + newLine + " name: " + telbook.personen.get(i).name + newLine + " adress: " + telbook.personen.get(i).adress + newLine + " city: " + telbook.personen.get(i).city + newLine + " phonenumber: " + telbook.personen.get(i).phonenumber);
ID++;
}
}
public void sortList() {
Collections.sort(telbook.personen);
}
}
phonebook class:
/**
* Created by ricardo on 2/26/2015.
*/
import java.util.*;
public class Phonebook {
ArrayList<Person> personen = new ArrayList<Person>();
}
person class:
/**
* Created by ricardo on 2/26/2015.
*/
public class Person {
String name, adress, phonenumber, city;
public Person(String name, String adress, String phonenumber, String city) {
this.name = name;
this.adress = adress;
this.city = city;
this.phonenumber = phonenumber;
}
// public String getCity() { return city; }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAdress() {
// return adress;
// }
//
// public void setAdress(String adress) {
// this.adress = adress;
// }
//
// public String getPhonenumber() {
// return phonenumber;
// }
//
// public void setPhonenumber(String phonenumber) {
// this.phonenumber = phonenumber;
// }
}
You should make your Person class implement the Comparable interface, and specifically tell how one should compare two Person objects.
An alternative is to implement a Comparator, and use Collections.sort(arrayList,comparator)
I'm working on a class assignment that accepts last name, first name and score for one or more students, stores them in an array and then sorts alphabetically by last name (or first name if last name is the same).
We're required to use a Student class that implements the Comparable interface.
As soon as I get to the Arrays.sort portion of the code, I get a ClassCastException stating that "Student cannot be cast to java.lang.Comparable".
I've searched and reviewed, tried to use implements Comparable<Student>, Clean and Build, but the error persists. Any help or hints are appreciated.
the error:
Exception in thread "main" java.lang.ClassCastException:
studentscoreapp.Student cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at studentscoreapp.StudentScoreApp.main(StudentScoreApp.java:35)
Java Result: 1 BUILD SUCCESSFUL (total time: 12 seconds)
Here's my Student class:
public class Student implements Comparable
{
private String lastName;
private String firstName;
private int score;
public Student(String fName, String lName, int s)
{
fName = firstName;
lName = lastName;
s = score;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
#Override
public int compareTo(Object obj)
{
Student sent = (Student) obj;
if (sent.lastName.equals(this.lastName))
{
return this.firstName.compareToIgnoreCase(sent.firstName);
}
else return this.lastName.compareToIgnoreCase(sent.lastName);
}
#Override
public String toString()
{
return lastName + firstName + score;
}
}
the Comparable interface:
public interface Comparable
{
int compareTo(Object obj);
}
and my main:
import java.util.Arrays;
public class StudentScoreApp
{
public static void main(String[] args)
{
String firstName;
String lastName;
int score;
System.out.println("Welcome to the Student Scores Application");
int numStudents = Validation.getInt("Enter # of Students: ");
Student[] studentArray = new Student[numStudents];
int i;
for (i = 0; i < numStudents; i++)
{
firstName = Validation.getString("Student [" + (i + 1) + "] first name: ");
lastName = Validation.getString("Student [" + (i + 1) + "] last name: ");
score = Validation.getInt("Student [" + (i + 1) + "] score: ", 0, 100);
studentArray[i] = new Student(firstName, lastName, score);
}
Arrays.sort(studentArray); //line 35
System.out.println();
//take each obj of the array and print the student info
for (Student obj : studentArray)
{
System.out.println(obj.toString());
}
}
}
Arrays.sort() accepts an array of objects which are subtypes of java.lang.Comparable. In your code, you have created your own Comparable interface, which, while it behaves the same way as java.lang.Comparable, is not the same interface.