ArrayList sorting tournament placings - java

Okay I cannot for the life of me figure out how to sort my data by tournament placings. Here is my code.
if (o == 5) {
double RD, t, old, x;
String tournament, player;
int a, number_of_players, place;
place = 0;
ArrayList<player> players = new ArrayList<player> ();
ArrayList<placeDisplay> placeVar = new ArrayList<placeDisplay> ();
List<placeDisplay> sort = new ArrayList<placeDisplay> ();
System.out.println("1:Add a tournament \t2:View Existing");
a = keyIn.nextInt();
if (a == 1) {
System.out.println("\nEnter tournament name");
tournament = keyIn.next();
System.out.println("\nEnter number of players");
number_of_players = keyIn.nextInt();
System.out.println("Enter players");
for (int i = 0; i < number_of_players; i++) {
String name = keyIn.next();
player plr = new player();
plr.setName(name);
players.add(plr);
}
System.out.println("\nEnter places for");
System.out.println(players);
for (int i = 0; i < players.size(); i++) {
System.out.println("\n" + players.get(i));
int places = keyIn.nextInt();
placeDisplay placer = new placeDisplay();
placer.setPlace(places);
placeVar.add(placer);
}
Collections.sort(sort);
System.out.println("\nThe Places are as follows");
for (int i = 0; i < players.size() && i < placeVar.size(); i++) {
System.out.println(placeVar.get(i) + ":" + players.get(i));
}
}
}
here is my public placeDisplay class file.
public class placeDisplay implements Comparable<placeDisplay> {
private int places;
public void setPlace(int nPlace) {
places = nPlace;
}
public int getPlace() {
return places;
}
#Override
public String toString() {
return Integer.toString(places);
}
#Override
public int compareTo(placeDisplay placeDisplay){
if (places > places)
return 1;
else if (places == places)
return 0;
else
return -1;
}
}
Here is the public class file
public class player {
private String name;
public void setName(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
#Override
public String toString() {
return name;
}
}
and here is my result on this portion of the program. Hope you guys can help me out on this one!
1:Add a tournament 2:View Existing
1
Enter tournament name
tournament1
Enter number of players
3
Enter players
Bob
Sally
John
Enter places for
[Bob, Sally, John]
Bob
2
Sally
1
John
3
The Places are as follows
2:Bob
1:Sally
3:John
Return to Main Menu? (Y/N)

Need to Modify your comparator method.
public int compareTo(placeDisplay placeDisplay){
if (places > placeDisplay.places)
return 1;
else if (places == placeDisplay.places)
return 0;
else
return -1;
}

Your compareTo is not right because you are comparing the same variable.
Change it to:
#Override
public int compareTo(placeDisplay placeDisplay){
if (places > placeDisplay.getPlace())
return 1;
else if (places == placeDisplay.getPlace())
return 0;
else
return -1;
}
Or even simply:
#Override
public int compareTo(placeDisplay placeDisplay){
return places - placeDisplay.getPlace();
}
I also suggest you to overwrite the equals method to make it consistent with your compareTo, as recommended in the Comparable interface documentation: "The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.".

Related

Getting Java methods from one object and a constructor from another object

I have three class Homework that has my main(...), GradeArray, which has my methods, and StudentGrade, which has my constructor.
Currently , which is clearly wrong, I have in Homework:
GradeArray grades = new GradeArray();`
In GradeArray at the top I have StudentGrade[] ArrayGrades = new StudentGrade[size]; however this method did not give me both the contructor and the methods. I know I don't need three classes for this but my professor wants three class. How do I declare an array that has attributes from two classes so that I can get the methods from GradeArray and the constructor from StudentGrade?
Thank you for you time and help.
Here is all of my code
package homework1;
public class Homework1
{
public static int pubSize;
public static String pubCourseID;
public static void makeVarsPub(int maxSize, String courseID) //this is to makes the varibles public
{
pubSize = maxSize;
pubCourseID = courseID;
}
public int giveSize()
{
return pubSize;
}
public static void main(String[] args)
{
int maxSize = 100;
String courseID = "CS116";
//this is to makes the varibles public
makeVarsPub(maxSize, courseID);
StudentGrade grades = new StudentGrade();
grades.insert("Evans", 78, courseID);
grades.insert("Smith", 77, courseID);
grades.insert("Yee", 83, courseID);
grades.insert("Adams", 63, courseID);
grades.insert("Hashimoto", 91, courseID);
grades.insert("Stimson", 89, courseID);
grades.insert("Velasquez", 72, courseID);
grades.insert("Lamarque", 74, courseID);
grades.insert("Vang", 52, courseID);
grades.insert("Creswell", 88, courseID);
// print grade summary: course ID, average, how many A, B, C, D and Fs
System.out.println(grades);
String searchKey = "Stimson"; // search for item
String found = grades.find(searchKey);
if (found != null) {
System.out.print("Found ");
System.out.print(found);
}
else
System.out.println("Can't find " + searchKey);
// Find average and standard deviation
System.out.println("Grade Average: " + grades.avg());
System.out.println("Standard dev; " + grades.std());
// Show student grades sorted by name and sorted by grade
grades.reportGrades(); // sorted by name
grades.reportGradesSorted(); // sorted by grade
System.out.println("Deleting Smith, Yee, and Creswell");
grades.delete("Smith"); // delete 3 items
grades.delete("Yee");
grades.delete("Creswell");
System.out.println(grades); // display the course summary again
}//end of Main
}//end of homework1
package homework1;
class GradeArray
{
int nElems = 0; //keeping track of the number of entires in the array.
Homework1 homework1InfoCall = new Homework1(); //this is so I can get the information I need.
int size = homework1InfoCall.giveSize();
StudentGrade[] ArrayGrades = new StudentGrade[size];
public String ToString(String name, int score, String courseID)
{
String res = "Name: " + name + "\n";
res += "Score: " + score + "\n";
res += "CourseID " + courseID + "\n";
return res;
}
public String getName(int num) //returns name based on array location.
{
return ArrayGrades[num].name;
}
public double getScore(int num) //returns score based on array location.
{
return ArrayGrades[num].score;
}
public void insert(String name, double score, String courseID) //part of the insert method is going to be
//taken from lab one and modified to fit the need.
{
if(nElems == size){
System.out.println("Array is full");
System.out.println("Please delete an Item before trying to add more");
System.out.println("");
}
else{
ArrayGrades[nElems].name = name;
ArrayGrades[nElems].score = score;
ArrayGrades[nElems].courseID = courseID;
nElems++; // increment the number of elements
};
}
public void delete(String name) //code partly taken from lab1
{
int j;
for(j=0; j<nElems; j++) // look for it
if( name == ArrayGrades[j].name)
break;
if(j>nElems) // can't find it
{
System.out.println("Item not found");
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
boolean go = true;
if ((k+2)>size)
go = false;
if(go)
ArrayGrades[k] = ArrayGrades[k+1];
}
nElems--; // decrement size
System.out.println("success");
}
}
public String find (String name){ //code partly taken from lab1
int j;
for(j=0; j<nElems; j++) // for each element,
if(ArrayGrades[j].name == name) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return ArrayGrades[j].toString();
}
public double avg() //this is to get the average
{
double total = 0;
for(int j=0; j<nElems; j++)
total += ArrayGrades[j].score;
total /= nElems;
return total;
}
public double std() //this is to get the standard deviation. Information on Standard deviation derived from
//https://stackoverflow.com/questions/18390548/how-to-calculate-standard-deviation-using-java
{
double mean = 0; //this is to hold the mean
double newSum = 0;
for(int j=0; j < ArrayGrades.length; j++) //this is to get the mean.
mean =+ ArrayGrades[j].score;
for(int i=0; i < ArrayGrades.length; i++) //this is to get the new sum.
newSum =+ (ArrayGrades[i].score - mean);
mean = newSum/ArrayGrades.length; //this is to get the final answer for the mean.
return mean;
}
public StudentGrade[] reportGrades() //this is grade sorted by name
{
int in,out;
char compair; //this is for compairsons.
StudentGrade temp; //this is to hold the orginal variable.
//for the first letter cycle
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(0);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(0) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
//this is for the second run.
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(1);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(1) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
return ArrayGrades;
}
public StudentGrade[] reportGradesSorted() //this is grades sorted by grades.
//this is grabbed from lab2 and repurposed.
{
int in,out;
double temp;
for(out=1; out<ArrayGrades.length; out++)
{
temp=ArrayGrades[out].score;
in=out;
while(in>0 && ArrayGrades[in-1].score>=temp)
{
ArrayGrades[in]= ArrayGrades[in-1];
in--;
}
ArrayGrades[in].score=temp;
}
return ArrayGrades;
} //end of GradeArray
package homework1;
public class StudentGrade extends GradeArray
{
public String name;
double score;
public String courseID;
public void StudentGrade (String name, double score, String courseID) //this is the constructor
{
this.name = name;
this.score = score;
this.courseID = courseID;
}
}//end of StudentGrade class.
First, I feel #Alexandr has the best answer. Talk with your professor.
Your question doesn't make it quite clear what you need. However, it sounds like basic understanding of inheritance and class construction would get you going on the right path. Each of the 3 classes will have a constructor that is unique to that type. Each of the 3 classes will have methods and data (members) unique to those types.
Below is just a quick example of what I threw together. I have strong concerns that my answer is actually what your professor is looking for however--it is not an object model I would suggest--just an example.
public class Homework {
private String student;
public Homework(String name) {
student = name;
}
public String getStudent() {
return student;
}
}
public class StudentGrade extends Homework {
private String grade;
public StudentGrade(String grade, String name) {
super(name);
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
public class HomeworkGrades {
public List<StudentGrade> getGrades() {
// this method isnt implemented but should
// be finished to return array of grades
}
}
Take a look and see if that helps you understand something about inheritance and class construction.
Hopefully you can infer a bit about inheritence (StudentGrade inherits -- in java extends -- from HomeWork) and class construction.
Thnx
Matt
I change the array creation in Homework1 to be StudentGrade grades = new StudentGrade(); and I added extends GradeArray to the StudentGrade class. it is now public class StudentGrade extends GradeArray.

Java youngest and oldest in an array of n

I have written a program to find the oldest and youngest person based on the ages and names that I have entered. The problem is, the program only gives me the oldest person, the else if statement for the youngest doesn't execute.
public class Boo {
public static void main(String[] strings) {
int[] age = new int[10];
String[] name = new String[10];
int count = 0;
Scanner in = new Scanner(System.in);
boolean notDone = true;
int smallest = age[0];
int largest = age[0];
String smalName = "";
String larName = "";
do {
System.out.println("Enter name");
name[count] = in.next();
if (!name[count].equalsIgnoreCase("done")) {
System.out.println("Enter age");
age[count] = in.nextInt();
if (age[count] > largest) {
largest = age[count];
larName = name[count];
}
else if (age[count] < smallest) {
smallest = age[count];
smalName = name[count];
}
}
else if (name[count].equalsIgnoreCase("done")) {
notDone = false;
}
count++;
}while(notDone && count < 3);
Your smallest variable is being instantiated to 0, because you set it to age[0], which being an array of integers has already been initialized to their default values of 0.
Try setting it to age[0] after you've first taken an age as an input, and then comparing subsequently.
int smallest = age[0];
int largest = age[0];
do
{
System.out.println("Enter name");
name[count] = in.next();
if (!name[count].equalsIgnoreCase("done"))
{
System.out.println("Enter age");
age[count] = in.nextInt();
if (count == 0)
{
smallest = age[0];
largest = age[0];
larName = name[0];
smalName = name[0];
}
else
{
if (age[count] > largest)
{
largest = age[count];
larName = name[count];
}
if (age[count] < smallest)
{
smallest = age[count];
smalName = name[count];
}
}
}
else if (name[count].equalsIgnoreCase("done"))
{
notDone = false;
}
count++;
} while (notDone && count < 3);
I would say it's best practice to separate it into 2 methods - one to get the youngest and on for the eldest. It will be clear to other developers who will might look at your code.
If that's not an option, you can use Pair in order to return two values. It meant to be for key and value but it enables you to return 2 values.
Your algorithm has some quirks that, maybe, you are not aware of. Your array age has been initialized by default. If you know what you are doing, it is not necessarily bad, but in this case it seems that you didn't. You are initializing the value of smallest and largest with values that are not in your list.
My advice is that you separate the recording of values from the computation of values.
EDIT: I mean something in this terms.
private class Person {
String name;
int age;
}
private Person enterPerson(Scanner sc) {
Person person = null;
String name = sc.next();
if(name != "done) {
int age = sc.nextInt();
person = new Person();
person.name = name;
person.age = age;
}
return person;
}
private Person youngest(List<Person> list) {
Person youngest = null;
for(Person person: list) {
if(youngest == null || youngest.age > person.age) {
youngest = person;
}
}
return person;
}
// Oldest would be equivalent

I want to search a specific element of an array and if it exists to return its index

I have created an array of type Savings which contains a String (Name) and a double (Account Number). I want to search using an Account Number and see if it exist and then return all the elements (Name + Account Number) and the Index of the Array that contain these elements. I tried this but it does not work.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Savings[] ArrayOfSavings = new Savings[5];
System.out.print("Enter Account Number: ");
Scanner scan = new Scanner(System.in);
double Ms = scan.nextDouble();
//Loop until the length of the array
for(int index = 0; index<= ArrayOfSavings.length;index++){
if(ArrayOfSavings[index].equals(Ms)){
//Print the index of the string on an array
System.out.println("Found on index "+index);
}
}
ArrayOfSavings[0] = new Savings("Giorgos",87654321);
ArrayOfSavings[1] = new Savings("Panos",33667850);
}
}
/Savings Class/
public class Savings extends Generic {
public Savings(String FN, double AN) {
super(FN, AN);
}
#Override
public String toString(){
return String.format("Customer: %s \n Acount Number: %.1f,
getFirstName(),getAccNumber();
}
}
You could do something like this, where you return -1 if it doesn't exist, or the index if you've found it. Just have to make sure you check for this case.
public static int findSavingsIfExists(double accountNumber, Savings[] allSavings) {
for(int i = 0; i < allSavings.length(); i++) {
if(allSavings[i].accountNumber == accountNumber) {
return i;
}
}
return -1;
}
and use it like so
int index = findSavingsIfExists(..., ArrayOfSavings);
if(index != -1) {
Savings foundSavings = ArrayOfSavings[index];
} else {
//Not found
}
Try to use somethig like this:
double Ms = scan.nextDouble();
int index = 0;
for (int i = 0; i < ArrayOfSavings.length; i++) {
if (ArrayOfSavings[i].getAccountNumber == Ms ) {
index = i;
break;
}
}
System.out.println(index);

ArrayList-"for-loop" exits code at .size() call, what's wrong?

As part of the login method for my fictive bank, i have a Luhn algorithm set up to validate the users ID.
It seems to check through and comes back valid, but when i list the ArrayList (with the for-loop) to see if there's a corresponding match or not, the code seems to breaks out when it hits kList.size()
See this :
public void logIn() {
System.out.print("Please enter your ID (10 numbers):");
String x = s.nextLine();
if (luhnCheck(x)) {
for (i = 0; i < k.kList.size(); i++) { //<-----ISSUE!
if (k.kList.get(i).getPnr().equals(x)) {
tempKund = k.kList.get(i);
}
}
} else {
System.out.println("You are not a customer, please register!");
System.out.print("Enter name:");
String n = s.nextLine();
k.createKund(x, n); //sends values to create customer method
kundMeny1(); // customer menu...
}
}
public boolean luhnCheck(String v) {
int sum = 0;
boolean alternate = false;
for (int i = v.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(v.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
Update: So apparently the problem doesn't seem to in the loop, but when the .size() tries to get the needed information. I'll paste some more of my code:
public class Bank {
Scanner s = new Scanner(System.in);
Kund k = new Kund(); //Used for communicating with the Kund(customer class)
Konto t = new Konto(); //Used for communicating with the Konto(account class)
Kund tempKund; //Temporary customer used to keep track of who's logged in
int i;
public static void main(String[] args) {
Bank b = new Bank();
b.mainMenu();
}
public void mainMenu() {
k.createKund("8908041207", "Adam Sears"); //Creates a customer
t.createKonto("1234567891", "3000"); //Creates a bank account
int user_choice = 3;
do { // Goes on to a Switch Case menu for the user...
Kund(Customer class)
public class Kund {
ArrayList<Kund> kList = new ArrayList<Kund>();
Kund knd;
String pnr; //Customer ID, used in validation
String name; //Customer name
public void kund() {
}
public String getPnr() {
return pnr;
}
public void setPnr(String x) {
this.pnr = x;
}
public String getName() {
return name;
}
public void setName(String z) {
this.name = z;
}
public void createKund(String p, String n) { //Creates the new customer
knd = new Kund();
knd.setPnr(p);
knd.setName(n);
addKund(knd);
}
public ArrayList<Kund> addKund(Kund s) { //Adds said customer to ArrayList
kList.add(s);
return kList;
}
This part of your code :
if (luhnCheck(x)) {
if (true) {
// Code
} else if (false) {
// Code
}
}
Should be replaced by this :
if (luhnCheck(x)) {
// Code
} else {
// Code
}
For the rest of the problem. I should know where you instantiate your k object.
We need more inforation on how k is instantiate, try to organize you snippet code, and try to debug at the
for (i = 0; i < k.kList.size(); i++) { //<-----ISSUE!
to see what kist contains?

Finding max/min value using Comparable

I have an object class
public class Film implements Comparable<Film>
I'm using Eclipse and would like to know why Film is underlined in red with the error saying:
The type Film must implement the inherited abstract method Comparable<Film>.compareTo<Film>
And now to my main question:
How would I get the max/min user submitted film length and title?
My object class Film has getter and setter methods for the Title of the film and the Length of the film and a toString method. Following this article (#3) I created two more methods in my object class:
public int max(Film maxLength){
int compareLength = ((Film) maxLength).getLength();
return this.length - compareLength;
}
public int min(Film minLength){
int compareLength = ((Film) minLength).getLength();
return compareLength - this.length;
}
Could I use these to find and print max/min values of the user submitted film lengths?
If so, how?
If not, what is the proper way of doing this?
The test class is as follows:
import java.util.Scanner;
public class test {
public static void main (String[] args){
Film[] f = new Film[3];
Scanner input = new Scanner(System.in);
for (int i=0;i<3;i++){
f[i] = new Film();
System.out.println("Enter Film Length:");
f[i].setLength(input.nextInt());
input.nextLine();
System.out.println("Enter Title:");
f[i].setTitle(input.nextLine());
}
input.close();
for (int i = 0; i < 3; i++) {
System.out.println(f[i].toString());
}
}
}
The Film class implements Comparable<Film>. What this means is that you must implement a method called compareTo() in class Film that will provide an ordering for objects of this class.
#Override
public int compareTo(Film that) {
// Order by film length
return Integer.compare(this.length, that.length);
}
If you only need to sort the objects by film length you can just use Arrays.sort():
Film[] films = new Film[3];
// put the objects into the array
Arrays.sort(films);
Then films[0] will contain the film with the shortest length, while the last element will be the film with the longest length.
If you need to compare by other fields, such as film title, you can create a custom comparator:
class FilmTitleComparator implements Comparator<Film> {
public int compare(Film a, Film b) {
return Integer.compare(a.getTitle().length(), b.getTitle().length());
}
}
And pass it to Arrays.sort()
FilmTitleComparator titleComparator = new FilmTitleComparator();
Arrays.sort(films, titleComparator);
Then films[0] will contain the film with the shortest title, while the last element will be the film with the longest title.
For simplicity, I stubbed your Film class to show a trivial example of how to implement Comparable
public class Film implements Comparable<Film> {
int maxLength;
int minLength;
String title;
public Film() {
this.maxLength = 0;
this.minLength = 0;
this.title = "";
}
// implement this method to accomplish comparison
public int compareTo(Film f) {
int result = 0; // the result to compute.
if ( this.equals(f) ) {
result = 0; // these objects are actually equal
}
// compare using meaningful data
else if ( f != null) {
// check to see if this film is greater than the specified film
if ( this.getMaxLength() > f.getMaxLength() ) {
// this film is comparatively greater, return > 0
result = 1;
}
else if ( this.getMaxLength() == f.getMaxLength() ) {
// these two films are comparatively equal
result = 0;
}
else {
// this film is comparatively less than the specified film
result = -1;
}
// similarly, you could also check min, but there's really no reason to do that unless your implementation calls for it.
}
else {
throw new IllegalArgumentException("null Film object not allowed here...");
}
return result;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Film film = (Film) o;
if (maxLength != film.maxLength) return false;
if (minLength != film.minLength) return false;
if (!title.equals(film.title)) return false;
return true;
}
#Override
public int hashCode() {
int result = maxLength;
result = 31 * result + minLength;
result = 31 * result + title.hashCode();
return result;
}
public int getMaxLength() {
return maxLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public int getMinLength() {
return minLength;
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
To fix your test to actually use such an implementation (it doesn't really test anything...), you could do:
import java.util.Scanner;
public class test {
public static void main (String[] args){
Film lastFilm = null; // arbitrary reference to film
Film[] f = new Film[3];
Scanner input = new Scanner(System.in);
for (int i=0;i<3;i++){
f[i] = new Film();
System.out.println("Enter Film Length:");
f[i].setLength(input.nextInt());
input.nextLine();
System.out.println("Enter Title:");
f[i].setTitle(input.nextLine());
}
input.close();
for (int i = 0; i < 3; i++) {
if ( lastFilm != null ) {
// compare the films to test. current to last film
if ( f[i].compareTo(lastFilm) > 0 ) {
System.out.println(f[i].getTitle() + " is greater than " + lastFilm.getTitle()");
}
else if ( f[i].compareTo(lastFilm) < 0 ) {
System.out.println(f[i].getTitle() + " is less than " + lastFilm.getTitle()");
}
else {
System.out.println(f[i].getTitle() + " is equal to " + lastFilm.getTitle()");
}
}
System.out.println(f[i].toString());
lastFilm = f[i];
}
}
}
Something like this can get you started... good luck
Another solution would be to implement Comparable<Film>:
#Override
public int compareTo(Film that) {
return this.length - that.length;
}
And use org.apache.commons.lang3.ObjectUtils#min or org.apache.commons.lang3.ObjectUtils#max like:
Film min = ObjectUtils.min(film1, film2);
Film max = ObjectUtils.max(film1, film2);

Categories