Searching for a String in an ArrayList of Objects - java

I have been trying to figure this out for hours and I have had no luck doing so,
I'm trying to iterate over my Arraylist<Booking> which utilizes my Booking class file and trying to understand how I'm able to search it for the matching, case-insensitive term.
this is my current method:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (int i = 0; i < bookings.size(); i++) {
while (!bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
i++;
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(), bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(), bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
}
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
I know it's messy but, just trying to make do.
I am trying to retrieve the name of the booking as I am searching by name as well as provide an error message if that names does not exist, to do that I must
use bookings.getStudent().getName() I have had some luck as I can return the value but now I am not able to provide my error message if I do not find it. Any help is appreciated.
package com.mycompany.mavenproject1;
public class Booking {
private Student student;
private int lessons;
private boolean purchaseGuitar;
// CONSTANTS
final int firstDiscountStep = 6;
final int secondDiscountStep = 10;
final int tenPercentDiscount = 10;
final int twentyPercentDiscount = 5;
final double LESSON_COST = 29.95;
final double GUITAR_COST = 199.00;
double LESSON_CHARGE = 0;
final int MINIUMUM_LESSONS = 1;
public Booking() {
}
public Booking(Student student, int lessons, boolean purchaseGuitar) {
this.student = new Student(student.getName(), student.getPhoneNumber(), student.getStudentID());
this.lessons = lessons;
this.purchaseGuitar = purchaseGuitar;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getLessons() {
return lessons;
}
public void setLessons(int lessons) {
this.lessons = lessons;
}
public boolean isPurchaseGuitar() {
return purchaseGuitar;
}
public void setPurchaseGuitar(boolean purchaseGuitar) {
this.purchaseGuitar = purchaseGuitar;
}
public double calculateCharge() {
double tempCharge;
if (lessons < firstDiscountStep) {
LESSON_CHARGE = (lessons * LESSON_COST );
} else if (lessons < secondDiscountStep) {
tempCharge = (lessons * LESSON_COST) / tenPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
} else {
tempCharge = (lessons * LESSON_COST) / twentyPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
}
if (isPurchaseGuitar()) {
LESSON_CHARGE += GUITAR_COST;
}
return LESSON_CHARGE;
}
#Override
public String toString() {
return student + ","+ lessons + "," + purchaseGuitar +"," + LESSON_COST;
}
}

If I understood you correctly, you are searching for a given student name in your collection of bookings. And if it is present, set a formatted text.
First of all, use a for-each loop, because you don't use the index.
Secondly, return from the for-each loop, when you found your student.
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (final Booking booking : bookings) // for-each
{
if (booking.getStudent().getName().equalsIgnoreCase(searchTerm))
{
String output = booking.getFormattedOutput();
this.taDisplay.setText(heading + "\n" + output + "\n");
return; // break out of the loop and method and don't display dialog message
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
Then there are multiple other things, which you could improve.
Don't get all the data from a booking just to format it externally. Let the Booking class handle the formatting and return you the string you desire. (move the formatting in a function inside the Booking class)
Instead of recreating a Student you receive in your Booking constructor, make the Student class immutable, and then you can just reuse the object provided.
Try also making the Booking class immutable. You provided some setters, but do you really want to change the student in a booking? Or would you rather create a new booking for the other student?
The calculteCharge method could be stateless. Just get the LESSON_CHARGE value and hold it in a local variable. Your method would also get threading-proof.
Make your constants final and better yet make them members of the class (by adding the static modifier) instead of every member.
Lastly, representing a money amount with a floating (double is better but not good either) number, you will run into funny situations. Try this calculation: 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 for example.
One way would be to create a Money class which holds the value in cents as an integer. And when you want to display the amount you can divide it by 100 and format it accordingly. That way, you can also restrict it become negative.
PS: Sometimes we desperately try to find a solution that we don't give ourselves some rest. After a little break, you might recognize the problem. Oh and try debugging with breakpoints. Or this, if you use IntelliJ IDEA (which I would highly recommend, the community edition is free).

You're re-incrementing your counter variable, which is really not going to help. Try the following:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
boolean studentFound = false;
for (int i = 0; i < bookings.size(); i++) {
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(),
bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(),
bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
studentFound = true;
break;
}
}
}
if (!studentFound) {
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
}

Related

How do I make a class to dynamic check different objects variable?

I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}

setters and getters in java

I have two files one is the driver, I'm having a problem with setters. It looks did set the value .
public class Movie {
private String name;
private int minutes;
protected int tomatoScore;
public Movie(String name, int minutes, int tomatoScore)
{
this.name=name;
this.minutes=minutes;
this.tomatoScore=tomatoScore;
}
public String getName() {return name;}
public void setName(String name) {this.name=name;}
public int getMinutes() {return minutes;}
public boolean setMinutes(int minutes) {return minutes>=0;}
public int getTomatoScore() {return tomatoScore;};
public boolean setTomatoScore(int tomatoScore) {return tomatoScore>=0 &&tomatoScore<=100;};
public boolean isFresh() {return tomatoScore>=60;};
public void display()
{
//this.name = name;
//this.minutes = minutes;
//this.tomatoScore =tomatoScore;
System.out.println("Movie: "+ getName());
System.out.println("Length: "+ getMinutes() +"min.");
if(tomatoScore>=60)
{
System.out.println("TomatoScore: Fresh");
}
else
{
System.out.println("TomatoScore: Rotten");
}
}
}
and bellow is the driver file if you notice the setters did do the job that is supposed to do I believe the problem is movie class, if you run the driver to test the program you see if you set the value to the negative the if statement does not function properly.( setMinutes and setTomatoScore are wrong. They do not set the class fields at all)
public class MovieDriver {
public static void main (String [] args){
Movie[] myCollection = new Movie[5];
myCollection[0] = new Movie("Batman The Dark Knight", 152, 94);
myCollection[1] = new Movie("Guardians of the Galaxy", 125, 91);
myCollection[2] = new Movie("The GodFather", 178, 98);
myCollection[3] = new Movie("Suicide Squad", 137, 27);
myCollection[4] = new Movie("Get out", 104, 99);
//TODO
//Initialize the variable below and add it to myCollection at index 4.
//You can pick any movie you wish.
Movie yourMovie;
System.out.println("Here are all the movies in my collection of movies.\n");
for(int i = 0; i < myCollection.length; i++) {
if(myCollection[i] != null)
myCollection[i].display();
}
System.out.println("_______________________________________________");
System.out.println("\nHere are the Fresh movies.");
for(int i = 0; i < myCollection.length; i++) {
if(myCollection[i] != null && myCollection[i].isFresh()) {
System.out.println(myCollection[i].getName() + " is fresh.");
}
}
System.out.println();
System.out.println("Here are the Rotten movies.");
for(Movie movieTmp: myCollection){
if (movieTmp != null && !movieTmp.isFresh())
System.out.println(movieTmp.getName() + " is rotten.");
}
System.out.println("_______________________________________________\n");
Movie harryPotter = new Movie("Harry Potter and the Prisoner of Azkaban", 144, 91);
System.out.println("The movie " + harryPotter.getName() + " was created.\n");
System.out.println("Is " + harryPotter.getName() + " a long movie?");
if(harryPotter.getMinutes() > 120) {
System.out.println("Yes, it is a bit long.\n");
} else {
System.out.println("Nope, that isn't too bad.\n");
}
System.out.println("Can I set the minutes of " + harryPotter.getName() + " to a negative number?");
harryPotter.setMinutes(-5);
if(harryPotter.getMinutes() == -5) {
System.out.println("It worked. The runtime is -5 minutes.\n");
} else {
System.out.println("It did NOT work. Negative runtimes are not allowed.\n");
}
System.out.println("Can I set tomato score of " + harryPotter.getName() + " to a negative number?");
harryPotter.setTomatoScore(-100);
if(harryPotter.getTomatoScore() == -100) {
System.out.println("It worked. The score is -100. This movie is terrible according to the site.\n");
} else {
System.out.println("It did NOT work. Negative scores are not allowed.\n");
}
System.out.println("Can I set tomato score of " + harryPotter.getName() + " to a number greater than 100?");
harryPotter.setTomatoScore(101);
if(harryPotter.getTomatoScore() == 101) {
System.out.println("It worked. The score is 101. Best Harry Potter movie ever!\n");
} else {
System.out.println("It did NOT work. Still the best Harry Potter movie out all the movies though.\n");
}
}
}
Your setMinutes and setTomatoScore methods don't set anything, they just return a boolean. I assume you've forgotten to add this.tomatoScore = tomatoScore for example.
As rzwitserloot mentioned, setter function for minutes and tomatoScore are not setting any thing.This might be the case.
Additional I would like add, I found it is better to use well known IDE for java programming like intellij, netBean, eclipse. They have provide many feature like auto generate setter, getter , constructor. So we can focus more on core logic and this saves our time and reduce possiblity of manual error.
One more point I would like to add,
It is better to use setter in the constructor, so before setting value is we want to perform any input validation,we can have that in setter and can use that even when setting value via constructor.
For an example,
public class Example {
private int x;
public Movie(int x){setMinutes(x);}
public void setX(int x) {
//some validation on input
if(x >= 0){this.x = x;}
public int getX() {return x;}
Looks like you need this:
public boolean setMinutes(int minutes) {
if(minutes >= 0 && minutes < 60) {
//I'm guessing the <60 part here, but whatever,
//this is how you'd set the 100 limit on your setTomatoScore method
this.minutes = minutes;
return true;
}
return false;
}
Make similar corrections for the setTomatoScore
​You need to set something tomatoScore in the state of methods as shown below​​ :
public boolean setTomatoScore(int tomatoScore) {
if (tomatoScore >= 0 && tomatoScore <= 100) {
this.tomatoScore = tomatoScore;
return true;
}
return false;
}

Creating a method that validates an ID-number according to certain specifics

I am developing a bank application. It's a school assignment (Java system development), it's my first year, I am still a novice. The purpose with the method I need help with is to validate a ID-number according different specifics.
I have used a part of this code, but modified it. Now when I have written the ID-number into the text-frame nothing happens. I am using card-layout. This method is located on the "register" panel. The idea is that the should be able to login at the next panel if the ID-number (and the password) is correct.
The code I is developed for a console, but I am trying to get it to work with a jFrame. I think this is quite a common school assignment here in Sweden and I don't think it's far-fetched to say that more pupils may have use of the help I may receive here.
public class BankFrame extends javax.swing.JFrame {
public BankFrame() {
initComponents();
} //This is the method that I have problems with:
private void registerBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Register customer = new Register(password);
if (password.equals("")){
outReg.setText("Enter a password as required.");
}
}
void CorrectId() {
//panel
}
public void CorrectId(String id) {
if (validateNumbers(id)) {
RegPanel.setVisible(false); // I am using CardLayout. This method is in the RegPanel.
LoginPanel.setVisible(true); //This shoul allow the user to change to the Login panel if the id is valideted by the method.
base.removeAll();
base.add(LoginPanel);
revalidate();
repaint();
} else {
outReg.setText("Enter a valid ID-number before proceeding");
while (true) {
id = (regIdIn.getText());
id = id.replaceAll("-", "").trim(); // A swedish ID number looks like this 890123-0000. I have to remove - to be able to run the method validateNumbers.
if (id.equals("")) { // A warning that should be written on the outReg label.
outReg.setText("Enter your id as required.");
break;
}
}
}
}
public boolean validateNumbers(String nm) { //new String so that "id" keeps it's values.
int numberSize = nm.length();
if (numberSize != 10) { // Warning if the ID-number has too little or too many numbers.
outReg.setText("Only 10 numbers is allowed!");
return false;
} else if (nm.matches("\\d+")) {
return true;
} else { //Warning if there is letters in the ID-number.
outReg.setText("You are kidding... I hope! ");
return false;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
The problem has been solved. Thank you for your help! I am posting the solution here:
Login newUser = new Login(savedId,password);
password = (regPasswordIn.getText());
if (password.equals("")){
outReg.setText("Enter a password as required.");
}else{
CorrectId();
}
}
public void CorrectId() {
id = (regIdIn.getText()); //Ta in id
id = id.replaceAll("-","").trim();
if (id.equals("")){
outReg.setText("Enter your id as required.");
}else{
if (validateNumbers(id)){
RegPanel.setVisible(false);
LoginPanel.setVisible(true);
base.removeAll();
base.add(LoginPanel);
revalidate();
repaint();
savedId=id;
}else{
outReg.setText("Enter a valid ID-number before proceeding"); //Varningstext som även kommer upp
}
}
}
public boolean validateNumbers(String nm) { //ny String nm för att inte köra över id.
System.out.println("Hej"+nm.length());//debugg
boolean returnvar;
numberSize = nm.length();
if (numberSize != 10) { // Felmeddelande ifall att fel antal siffror är ifyllda.
outReg.setText("Only 10 numbers is allowed!");
returnvar= false;
} else {
returnvar= true;
}
return returnvar;
}
private void infoBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Genom desssa olika Randomgeneratorer tar jag fram ett unikt kontnummer.
//Clearingnummer :
while (true){
Random clearingNum = new Random ();
int clrRange = 8999-7000; //Formel för swedbanks clearing nummer
int clr = clearingNum.nextInt(clrRange) + 70000;
// Sista siffran i clearingnumret
Random clrDiget = new Random();
int clrDrange = 9 - 1;
int clrD = clrDiget.nextInt(clrDrange)+1;
//Siffrona i själva kontonumret
Random actNum = new Random();
int actRange = 999999999-100000000; //Formel för swedbaks kontonummer
int act = actNum.nextInt(actRange) + 100000000;
//Sista siffran i kontonumret
Random actDiget = new Random();
int actDrange = 9 - 1 + 1;
int actD = actDiget.nextInt(actDrange) + 1;
String a = ""+clr; //Konverterar int från randomgeneratorerna till String.
String b = ""+clrD;
String c = ""+act;
String d = ""+actD;
String accountNumber = a + "-" +b + "," +c +"-" +d; //Sätter ihop kontonumrets olika delar i korrektformat.
accountNumberOut.setText(accountNumber); //Skriver ut kontinummret.
break;
}
Customer accountNumber = new Customer(name,phone,email); //Deklarerar nytt konto. Lagrat värden i konstruktorn!
firstName = (firstNameIn.getText());
surName = (surNameIn.getText());
name = firstName + "" + surName;
phone = (phoneIn.getText());
email = (emailIn.getText());
out.setText("Customer: " +name+ "Phone: " +phone+ "Email: " +email);
}

Calculate column data

i'm trying to create a void method that will read csv file and count the reputaion number of state such that how many times TX,how many times Oh and how many times of Dc. the out should be-TX=4; Oh=2;DC=2. but my out put is "For input string: "F" "- and i really couldn't get where is the problem.can someone help me?
"Crimerate.csv"
State county Rate
Tx,DALLAs,39
TX,Aderson,10
Oh,Archer,20
DC,DC,50
Tx,Houston,31
TX,Claude,13
Oh,Bexar,10
DC,SE,40
public static void countnumber()
{
try{
List<String>number=Files.readAllLines(Paths.get("Crimerate.csv"));
double sum=0,num=0;
for (String line:number){
if(num==0){
++num;
continue;
}
line=line.replace("\"","");
String []result=line.split(",");
double close = Double.parseDouble(result[6]);
String numberAsString = Double.toString(close);
if(numberAsString.equals("Tx"))
{
sum++;
System.out.println("number of Tx =" + sum);
}
else if(numberAsString.equals("Oh"))
{
sum++;
System.out.println("number of Oh =" + sum);
}
else if(numberAsString.equals("Dc"))
{
sum++;
System.out.println("number of Dc =" + sum);
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void main (String args[])
{
countnumber();
}
While the previously suggested answers will address the specific question of why there was only a single response (a result of having only a single sum variable), they have two issues.
They are not accounting for the fact that in the example data, Texas is shown both as "Tx" and "TX". Thus, the current other answers will not give the correct result of 4 for Texas (they will only show 2).
The approaches assume that the full data set was shown. If other states are present, then the code would need to be continually expanded to support the new states.
This solution handles both situations.
public static void main(String[] args)
{
Map<String, Integer> countByState = new HashMap<>();
List<String> number;
try {
number = Files.readAllLines(Paths.get("f:/tmp/Crimerate.csv"));
int cntr = 0;
for (String line : number) {
// skip first line
if (cntr++ == 0) {
continue;
}
String []result=line.split(",");
// should add error checking
String state = result[0].toUpperCase();
Integer cnt = countByState.get(state);
if (cnt == null) {
cnt = new Integer(0);
}
countByState.put(state, ++cnt);
}
System.out.println(countByState);
}
catch (IOException e) {
e.printStackTrace();
}
}
Sample Results based upon the data presented in the question (there is only one DC in that data):
{TX=4, OH=2, DC=1}
int txCount = 0;
int ohCount = 0;
int dcCount = 0; //create this variables inside the class(instance variables)
if(numberAsString.equals("Tx"))
{
++txCount;
System.out.println("number of Tx =" + txCount);
}
else if(numberAsString.equals("Oh"))
{
++ohCount;
System.out.println("number of Oh =" + ohCount);
}
else if(numberAsString.equals("Dc"))
{
++dcCount;
System.out.println("number of Dc =" + dcCount);
} //its better if u use equalsIgnoreCase on if Statements
you were referring to same sum variable on each if loops, i have fixed that .
i assume that the code you have written on reading the file is correct.
You just need different sum variables for each sum. And print the results after the loop.
try{
List<String>number=Files.readAllLines(Paths.get("Crimerate.csv"));
double sumTx=0,sumOh=0,sumDc=0,num=0;
for (String line:number){
if(num==0){
++num;
continue;
}
line=line.replace("\"","");
String []result=line.split(",");
double close = Double.parseDouble(result[6]);
String numberAsString = Double.toString(close);
if(numberAsString.equals("Tx")) {
sumTx++;
} else if(numberAsString.equals("Oh")){
sumOh++;
} else if(numberAsString.equals("Dc")){
sumDc++;
}
}
System.out.println("number of Tx =" + sumTx);
System.out.println("number of Oh =" + sumOh);
System.out.println("number of Dc =" + sumDc);
}catch(Exception e){
System.out.println(e.getMessage());
}
}

How to compare parameter values of two objects in Java?

Right now I'm working on a method for comparing the scores of athletes in the olympics. So far I've had little trouble, however now I've reached a point where i need to compare two objects (athletes) scores and I'm not sure how to do it. This is my code for the Olympic class:
// A program using the Athlete class
public class Olympics {
public static void main(String args[]) {
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
System.out.println(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
System.out.println(tessa);
System.out.println(); // blank line
tessa.addScore(50);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(100);
meryl.addScore(65);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(20);
System.out.println("Tessa's final score is " + tessa.getScore());
meryl.move("France");
System.out.println(meryl);
} // end main
} // end class Olympics
And this is the constructor class "Athlete":
public class Athlete {
private String name;
private String country;
protected int score;
public static int leadScore;
public Athlete(String athName, String athCountry) {
this.name = athName;
this.country = athCountry;
score = 0;
if (score < 1) {
System.out.println("Score cannot be lower than 1");
}
}
public int addScore(int athScore) {
score += athScore;
return score;
}
public static String leader(){
//TODO
}
public static int leadingScore() {
//MUST COMPARE BOTH ATHLETES
}
public int getScore(){
return score;
}
public void move(String newCountry) {
country = newCountry;
}
public String toString() {
return name + ": " + "from " + country + ", current score " + score;
}
}
So what I'm trying to do is have the program check Meryl's score compared to Tessa's and return that Athlete's score in leadingScore() and, using that athlete, return a leader(). Any help is appreciated! Thanks.
The function must take the two Athletes you're comparing as the parameters for this to work
public static int leadingScore(Athlete a1, Athlete a2) {
if (a1.getScore() < a2.getScore()) {
// do stuff
}
}
The lead score should not be in the athlete class, but rather in main () because one instance of an Athlete class would not know of other instances unless you put a self-referential list inside the class. Similarly, leadingScore should be in main ().
It or main can call each athlete and compare:
int merylScore = meryl.getScore ();
int tessaScore = tessa.getScore ();
int leadingScore = 0;
String leaderName = "";
if (merylScore > tessaScore) {
leadingScore = merylScore;
leaderName = meryl.getName ();
} else if (tessaScore > merylScore) {
leadingScore = tessaScore;
leaderName = tessa.getName ();
} else {
leadingScore = merylScore;
leaderName = "a tie between Meryl and Tessa";
}
System.out.println ("The leader is " + leaderName + ", with a score of " + leadingScore);
You should consider using a "collection". Use an array, a list ... or even a sorted list.
Stored your individual objects in the collection, then traverse the collection to find the highest score.
For example:
// Create athlete objects; add each to list
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
...
athletes.add(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
...
athletes.add(tessa );
// Go through the list and find the high scorer
Athlete highScorer = ...;
for (Athlete a : athletes) {
if (highScorer.getScore() < a.getScore())
highScorer = a;
...
}
System.out.println("High score=" + highScorer.getScore());
Here's a good tutorial:
http://www.vogella.com/tutorials/JavaCollections/article.html

Categories