I'm trying to do this exercise: i have a student that has a name,surname and a number, i want to order the students by number..if i want to order by name or surname it seems easy but with number i don't know how to do..
this is my code:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo Name
public int compareTo(Student otherObject) {
return name.compareTo(otherObject.getName());
}
}
//TESTER
ArrayList<Student> list = new ArrayList<Student>();
System.out.print("\n ORDER BY NUMBER \n");
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
String std = s.getAll();
System.out.println(std);
}
You can implement something like:
public int compareTo(Student otherObject) {
return Integer.compare(this.number, otherObject.getNumber());
}
So why you number is an int you can substract the number and return the difference:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo number
public int compareTo(Student otherObject) {
return number - otherObject.getmatricola();
}
}
Try doing this...should work
//CompareTo Name
public int compareTo(Student otherObject) {
if( this.getmatricola() > otherObject.getmatricola())
return 1;
else
return -1;
}
Related
Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work
//package Driver2;
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
r = this.customerPurchase;
if (r > 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public int getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;
//Constructors
/* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
super();
this.customerPurchase = customerPurchase;
//this.customerDiscount = customerDiscount;
}*/
public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
//super(name, address, number, customerPurchase, customerN, rm);
//this.customerPurchase = customerN;
//this.customerDiscount = pc;
}
public Driver1()
{}
//Accessors
/*
public int getcustomerDiscount()
{
return this.customerDiscount;
}
/*
#Override
public int getcustomerPurchase()
{
return this.customerPurchase;
}
//Mutators
#Override
public void setcustomerPurchase(int c)
{
this.customerPurchase = c;
}*/
/*
public void setcustomerDiscount(int r)
{
this.customerPurchase = r;
if (r >= 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
System.out.println("Percent off: "+customer.getcustomerDiscount());
}
}
The code you have pasted require some changes actually.Assuming you need to return the discount percentage based on the customer input you need to do the following changes.
1) You have a setCustomerDiscount in Person class but the entity you are dealing here is of Customer type so you need to add the setCustomerDiscount in the Customer class instead of Person class.
2) As you want to show the percentage in String(as per your sysout statements/ you can also change to Int as required) you need to change the return type to String instead of Int.
3) Another thing is your order of the if/else if conditions should be in descending order.
Once you fix them, you can get your output as expected.
Below I have made those changes:
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public String getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
public void setcustomerDiscount(int r)
{
String customerDiscount = "";
if (r >= 2000)
{
customerDiscount="10%";
System.out.print("10%");
}
else if (r >= 1500)
{
customerDiscount="7%";
System.out.print("7%");
}
else if (r >= 1000)
{
customerDiscount="6%";
System.out.print("6%");
}
else if (r > 500)
{
customerDiscount="5%";
System.out.print("5%");
}
else
{
System.out.print("");
}
this.customerDiscount = customerDiscount;
}
}
public class TestMain
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
scanner.close();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
customer.setcustomerDiscount(customerPurchase);
System.out.println("Percent off: "+ customer.getcustomerDiscount());
}
}
Hope it helps...
I think it is a logical problem. Simply order the discount formula in reverse.
Catch the big numbers first:
if r >= 2000 print 10%
else if r >= 1500 print 7%
else if r >= 1000 print 6%
else if r >= 500 print 5%
else print nothing
I hope that helps you
This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 5 years ago.
How can I remove a student from the course by using the drop method down below? I tried by accessing the roll book for the course parameter.
But I do not how to remove the student id from the roll book.
public static class Student {
private int studentID;
private String first;
private String last;
private int credits;
private boolean graduate;
public Student(int id, String first, String last, boolean graduate) {
this.studentID = id;
this.first = first;
this.last = last;
this.graduate = graduate;
}
public int getID() { return studentID; }
public String getFirstName() { return first; }
public String getLastName() { return last; }
public int getCredits() { return credits; }
public boolean isGraduate() { return graduate; }
public void setCredits(int credits) { this.credits = credits; }
public String toString() { return "[" + studentID + "] " + first + " " + last; }
public boolean isEnrolled(Course c) {
return (c.findRollBookEntry(this.getID()) != null);
}
public void drop(Course c) {
for(int i = 0; i<c.getRollBook().length; i++){
c.findRollBookEntry(i).getStudent();
}
}
}
If you are using an array list and passing new objects each time a data is entered you can iterate through the arraylist on the delete function and do something like
If(i.getID()==id_entered) {i.remove();}
I am trying to search in a list but I sort as array so that I convert my linked list to array list but when I compile it without this part below. Command prompt gives "Person is not abstract and does not override abstract method compareTo(Person) in Comparable".
How can I fix this?
public int compareTo(Person other){
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
return this.name + " "+other.name;
}
Search list and sort methods:
public void searchList(String search)
{
if(phoneList.size() == 0){
System.out.println("There is no record phone book.");
}
Node<Person> tempNode = phoneList.head;
SLinkedList<Person> tempList = new SLinkedList();
for(int i=1; i<=phoneList.size; i++)
{
if (tempNode.getElement().getName().contains(search) || tempNode.getElement().getSurname().contains(search) || tempNode.getElement().getAddress().contains(search) || tempNode.getElement().getCell().contains(search) || tempNode.getElement().getHome().contains(search) || tempNode.getElement().getWork().contains(search))
{
tempList.addLast(tempNode.getElement());
personArray = new Person[tempList.size()];
Iterator<Person> it = tempList.iterator();
while(it.hasNext()){
int x = 0;
personArray[x] = it.next();
x++;
}
bubbleSort(personArray );
for(int x = 0; x < tempList.size(); x++)
System.out.println((x+1) + ""+ personArray[x]);
}
tempNode = tempNode.getNext();
}
}
public <AnyType extends Comparable<? super AnyType>> void bubbleSort(AnyType[] a) {
int outer, inner;
for (outer = a.length - 1; outer > 0; outer--) { // counting down
for (inner = 0; inner < outer; inner++) { // bubbling up
if (a[inner].compareTo(a[inner + 1]) > 0) { // if out of order...
//then swap
swapReferences(a,inner,inner+1);
}
}
}
}
public <AnyType> void swapReferences( AnyType [ ] a, int index1, int index2 )
{
AnyType tmp = a[ index1 ];
a[ index1 ] = a[ index2 ];
a[ index2 ] = tmp;
}
Person Class:
public class Person implements Comparable<Person>
{
private String name;
private String surname;
public String address;
public String cell;
public String home;
public String work;
public Person(String name, String surname, String address, String cell, String home, String work)
{
this.name = name;
this.surname = surname;
this.address = address;
this.cell = cell;
this.home = home;
this.work = work;
}
// Accessor methods:
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
public String getAddress(){
return address;
}
public String getCell(){
return cell;
}
public String getHome(){
return home;
}
public String getWork(){
return work;
}
// Modifier methods:
public void setName(String name){
this.name = name;
}
public void setSurname(String surname){
this.surname = surname;
}
public void setAddress (String address){
this.address = address;
}
public void setCell (String cell){
this.cell = cell;
}
public void setHome (String home){
this.home = home;
}
public void setWork (String work){
this.work = work;
}
public String toString(){
return name + " " + surname + " " + address + " " + cell + " " + home + " " + work;
}
public int compareTo(Person other){
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
return this.name + " "+other.name;
}
}
Your existing compareTo method has a problem, but removing it violates the implements Comparable contract, since you must provide a compareTo method.
public int compareTo(Person other) {
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
// next line returns a String, but the method needs to return an int
return this.name + " " + other.name;
}
You can instead rely more directly on the standard String compareTo:
public int compareTo(Person other) {
if ( this.name.equalsIgnoreCase( other.name ) ) { return 0 };
return this.name.compareTo( other.name );
}
If you didn't have the ignore case constraint you've coded for, this would simply be
public int compareTo(Person other) {
return this.name.compareTo( other.name );
}
As an aside, there is no reason to make address, cell, home, and work public — and that's generally bad practice.
In order to implement an interface you need to implement all the methods in that interface. You either remove implements Comparable part or add public int compareTo method to your class.
The rule of compareTo method is that :
- if this Person is greater than other , return 1
- if this Person is smaller than other , return -1
- if they are equal, return 0
I am trying to get the length of the longest first name and saving it as int longest, but my code is not properly fetching the first names from my class Student
here is my code:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (int i = 0; i < studentList.size(); i++)
{
if (studentList.get(i).getFirstName.length() > longest);
{
longest = studentList.get(i).getFirstName.length();
}
}
return longest;
}
Here is where I am fetching my variables:
public class Student
{
private int IDnum;
private String firstName;
private String lastName;
private int gradYear;
private double gradePoint;
public Student(int ID, String first, String last, int year, double GPA)
{
IDnum = ID;
firstName = first;
lastName = last;
gradYear = year;
gradePoint = GPA;
}
public int getID()
{
return IDnum;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getYear()
{
return gradYear;
}
public double getGPA()
{
return gradePoint;
}
}
getFirstName is not a variable, it's a method. Java syntax requires parentheses when calling a method (even if the method takes no arguments):
if (studentList.get(i).getFirstName().length() > longest);
^^
(and on the next line).
By the way, you can replace the entire if construct with:
longest = Math.max(studentList.get(i).getFirstName().length(), longest);
To simplify this further, you could use a for-each loop:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (Student student : studentList) {
longest = Math.max(student.getFirstName().length(), longest);
}
return longest;
}
Your code seems fine however there is a semi colon at the end of your if statement which is causing the issue.
I'm making a phone book and filling it with entries. The entries consist of two Strings for surname and initial, and a telephone number. I'm using an array to store the entries. I'm trying to get the array to print out and I've put toString methods in each class. But when I print out i'm still getting "[LEntry;#8dc8569". I'm not sure what I'm doing wrong. Here's the code.
public class Entry {
String surname;
String initial;
int number;
public Entry(String surname, String initial, int number) {
this.surname = surname;
this.initial = initial;
this.number = number;
}
public String getSurname(){
return surname;
}
public String getInitial(){
return initial;
}
public int getNumber() {
return number;
}
void setNumber(int number){
this.number = number;
}
public String toString(){
return surname+ "\t" +initial+ "\t" +number;
}
}
public class ArrayDirectory {
int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
public void addEntry(String surname, String initial, int num) {
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
}
public void deleteEntry(String surname, String initial) {
int i = findEntryIndex(surname, initial);
directory[i] = null;
}
public void deleteEntry(int number) {
int i = findEntryIndex(number);
directory[i] = null;
}
public int findEntry(String surname, String initial) {
int i;
i = findEntryIndex(surname, initial);
return directory[i].getNumber();
}
public void editNum(String surname, String initial, int number) {
int i;
i = findEntryIndex(surname, initial);
directory[i].setNumber(number);
}
public void print() {
// TODO print array
System.out.println(directory);
}
private int findEntryIndex(String surname, String initial) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getSurname().equals(surname) && directory[i].getInitial().equals(initial))
{
break;
}
}
return i;
}
private int findEntryIndex(int number) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getNumber() == number)
{
break;
}
}
return i;
}
private int findFreeLocation() {
int i;
for (i = 0; i < DIRECTORY_SIZE; i++)
{
if(directory[i] == null)
{
break;
}
}
return i;
}
public String toString() {
for(int i = 0 ; i< DIRECTORY_SIZE ; i++){
System.out.println( directory[i] );
}
return null;
}
}
public class Test {
public static void main(String[] args) {
ArrayDirectory phoneBook = new ArrayDirectory();
phoneBook.addEntry("Bigger", "R", 2486);
phoneBook.addEntry("Smaller", "E", 0423);
phoneBook.addEntry("Ringer", "J", 6589);
phoneBook.addEntry("Looper", "T", 6723);
phoneBook.addEntry("Lennon", "B", 4893);
phoneBook.addEntry("Martin", "M", 2121);
phoneBook.print();
}
}
Use Arrays.toString();
Arrays.toString(directory);
when you just print directory, which is an instance of array of type Entry, it doesn't override the toString() method the way you are expecting
Also See
Why isn't there a java.lang.Array class? If a java array is an Object, shouldn't it extend Object?