I'm writing a program with two classes, one person class and one main. The person class use get and set for six people and then the main class ask for the names and then show the user the six names (in my example it only shows four). Is it possible to use a loop for this? I know I could use a list for this but it's for school and they want us to use constructors, set and get in the first week or so. The code now looks like this. Is this even possible with an example like this or do I need to use a list or an array?
PersonClass.java
public class PersonClass {
private String namn;
public void setNamn(String namn) {
this.namn = namn;
}
public String getNamn() {
return namn;
}
}
MainClass.java
import javax.swing.*;
public class MainClass {
public static void main(String[] args) {
PersonClass person1 = new PersonClass();
PersonClass person2 = new PersonClass();
PersonClass person3 = new PersonClass();
PersonClass person4 = new PersonClass();
String namn1 = JOptionPane.showInputDialog("Enter full name for person 1!");
person1.setNamn(namn1);
String namn2 = JOptionPane.showInputDialog("Enter full name for person 2!");
person2.setNamn(namn2);
String namn3 = JOptionPane.showInputDialog("Enter full name for person 3!");
person3.setNamn(namn3);
String namn4 = JOptionPane.showInputDialog("Enter full name for person 4!");
person3.setNamn(namn4);
JOptionPane.showMessageDialog(null, "Person 1: " + person1.getNamn() +
"\nPerson 2: " + person2.getNamn() + "\nPerson 3: " + person3.getNamn() +
"\nPerson 4: " + person4.getNamn());
}
}
I'm personally a fan of Lists as well, but Arrays are just as good of an option. I build the output as it goes with a little String.format help.
List<PersonClass> persons = new ArrayList<PersonClass>();
String output = "";
for(int i = 1; i <= 6; i++) {
String name = JOptionPane.showInputDialog(String.format("Enter full name for person %d!", i));
PersonClass person = new PersonClass();
person.setNamn(name);
persons.add(person);
output += String.format("Person %d: %s\n",i, person.getNamn());
}
JOptionPane.showMessageDialog(null, output);
Hello because of your tone when suggesting arrays I take it that you are not comfortable with the concept yet, but maybe talk with your teacher about this and about the answers you get here!
PersonClass[] personArray = {person1, person2, person3, person4};
for (int i = 0; i < personArray.length; i++)
{
// (i + 1) because our array starts at 0, but it's the 0 + 1th person
String msg = "Enter full name for person" + (i + 1);
personArray[i].setName(JOptionPane.showInputDialog(msg));
}
List<PersonClass> people = new ArrayList<PersonClass>;
for (int i = 0; i < 6; i++) { // set i to number of required people
PersonClass person = new PersonClass();
person.setNamn(JOptionPane.showInputDialog("Enter full name for person " + (i + 1) +"!");
people.add(person);
JOptionPane.showMessageDialog(null, person.getNamn());
}
people will contain all the new PersonClass you created.
PersonClass[] persons = new PersonClass[4];
for(int i = 0; i < persons.length; i++){
persons[i] = new PersonClass();
persons[i].setNamn(JOptionPane.showInputDialog("Enter full name for person " + (i+1));
}
If dialog will be closed - there will be null returned.
One way to do this with a loop would be to make your main class like this. See comments:
import java.util.ArrayList;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
ArrayList<PersonClass> people = new ArrayList<PersonClass>();
int index=5;
//Loop that will ask for 6 names
for(int ii=0; ii<=index; ii++){
//create person object
PersonClass person = new PersonClass();
//get/set the name
person.setNamn(JOptionPane.showInputDialog("Enter full name for person " + ii + " !"));
//save name in arraylist
people.add(person);
}
int count = 1;
//will output names via a loop
for(PersonClass person : people){
if(person.getNamn() != null){
JOptionPane.showMessageDialog(null, "Person " + count + " name: " + person.getNamn());
}
count++;
}
}
}
If it were me, I'd create a custom constructor for the PersonClass, which sets the namn on construction:
public class PersonClass {
private String namn;
//Custom constructor using a setter
public PersonClass(String namn){
this.setNamn(namn);
}
public void setNamn(String namn) {
this.namn = namn;
}
public String getNamn() {
return namn;
}
}
Then I would do this in my MainClass:
import java.util.ArrayList;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
ArrayList<PersonClass> people = new ArrayList<PersonClass>();
int index=5;
//Loop that will ask for 6 names
for(int ii=0; ii<=index; ii++){
//create, set, and add name to list
people.add(new PersonClass(JOptionPane.showInputDialog("Enter full name for person " + ii + " !")));
}
int count = 1;
for(PersonClass person : people){
if(person.getNamn() != null){
JOptionPane.showMessageDialog(null, "Person " + count + " name: " + person.getNamn());
}
count++;
}
}
}
Related
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];
}
}
So here's the question I need to answer: Implement a method that takes a research area as an input and returns the names of scientists associated with that area.
I've got a lot of the base code necessary but am struggling because I am trying to filter out the array of scientist professions to only return the scientist whose profession is the specified input. What I need help with is finding a way to make a new array with only certain filtered scientists and excluding the unspecified scientist. Any idea on how to change the code to return an array of only certain scientists would be very helpful! The issue is in the CheckField method, and I'll put my code below of the program:
public class computerScientists {
String name;
String researchArea;
String contribution;
// Constructor
public computerScientists(String NM, String RA, String C) {
this.name = NM;
this.researchArea = RA;
this.contribution = C;
}
public static void main(String[] args) {
computerScientists[] personDatabase = {
new computerScientists("Katherine Johnson", "Mathematician", "Mathmetician for NASA during space race"),
new computerScientists("Kimberely Bryant", "Entrepreneur & Activist", "Founded black girls code"),
new computerScientists("Mark Dean", "Inventor and Engineer", "Helped design and release some of the first computers"),
new computerScientists("Marie Van Brittan Brown", "Inventor and Pioneer", "Pieneered and invented an audio-video alarm system"),
new computerScientists("Marian R Croak", "Engineer", "Helped develop the Voice Over Internet Protocol (VOIP)")
};
//int size = person1.length
for(int i=0; i<personDatabase.length; i++){
System.out.println("Innovator " + String.valueOf(i + 1) + ": \n");
System.out.println("Name: " + personDatabase[i].name + "\n"
+ "Research Area: " + personDatabase[i].researchArea + "\n"
+ "Contribution: " + personDatabase[i].contribution);
System.out.println();
}
checkField("Inventor", personDatabase);
}
public static computerScientists[] checkField(String researchField, computerScientists[] array1) {
computerScientists[] newArray1 = new computerScientists[array1.length];
//int difference = newArray1.length - array1.length;
for (int i=0; i < array1.length; i++) {
if (array1[i].researchArea.contains(researchField)) {
newArray1[i].researchArea = String.valueOf(array1[i]);
}
}
for (int j=0; j<newArray1.length; j++) {
System.out.println(newArray1[j].researchArea);
}
return newArray1;
}
}
In my program, I have a Vendor class and a Hospital class and store instances of these classes in arraylists called vendors and hospitals. My Vendor class has a string array with names of hospitals that correspond to instances of the Hospital class. I'm trying to find a way to go from the name of the hospital in the string array that is part of the Vendor class, to getting the index value of that hospital for the hospitals arraylist. Apologies if this post doesn't make much sense, I'm very new to coding. Any help would be greatly appreciated.
Edit: Please Ctrl+F with the following to jump to the particular lines of code in question
//check if hospital
Vendor Class
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Vendor {
//static variables are the same for all vendor instances
static int numOfHospitals;
static int numOfAppointments;
//non-static variables are specific to one vendor instance
int priorityNum;
String salespersonName;
String vendorCompanyName;
String [] vendorPicks;
String[] vendorSchedule;
public void printVendorSchedule() {
System.out.println(Arrays.toString(vendorSchedule));
}
public void printVendorPicks () {
System.out.println(Arrays.toString(vendorPicks));
}
public String getVendorSchedule (int appointmentSlot) {
return vendorSchedule [appointmentSlot];
}
public String getVendorPick (int currentHospitalPick) {
return vendorPicks[currentHospitalPick];
}
public boolean checkVendorSchedule (int appointmentSlot) {
return ((vendorSchedule[appointmentSlot]).equals("open"));
}
public void setVendorAppointment (int appointmentSlot, String hospitalName) {
vendorSchedule[appointmentSlot] = hospitalName;
}
public Vendor createNewVendor(int priorityNum, int numOfAppointments, int numOfHospitals, String salespersonName, String vendorCompanyName){
this.priorityNum=priorityNum;
this.salespersonName=salespersonName;
this.vendorCompanyName=vendorCompanyName;
this.vendorPicks = new String[numOfHospitals];
this.vendorSchedule = new String[numOfAppointments];
for (int i = 0; i <numOfAppointments; i++) {
this.vendorSchedule[i] = "open";
}
Scanner input = new Scanner(System.in);
Vendor vendorToAdd = new Vendor();
//loop to add vendor's hospital picks
int counter = 0;
while (counter < numOfHospitals) {
System.out.println("Enter the #" +(counter+1) +" hospital for "+salespersonName+". If there are no more hospitals for this vendor, enter Done.");
String placeHolder = input.nextLine();
if (placeHolder.equalsIgnoreCase("done")) {
break;
}
vendorPicks[counter]=placeHolder;
counter++;
}
return vendorToAdd;
}
}
Hospital Class
package com.company;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class Hospital {
//static variables here
int numOfAppointments;
int numOfHospitals;
//non-static variables here
String nameHospital;
String nameDirector;
String [] hospitalSchedule;
public void printHospitalSchedule () {
System.out.println(Arrays.toString(hospitalSchedule));
}
public String getHospitalSchedule(int appointmentSlot) {
return hospitalSchedule[appointmentSlot];
}
public boolean checkHospitalSchedule (int appointmentSlot) {
return ((hospitalSchedule[appointmentSlot]).equals("open"));
}
public void setHospitalAppointment (int appointmentSlot, String nameVendor) {
hospitalSchedule[appointmentSlot] = nameVendor;
}
public Hospital createNewHospital(int numOfAppointments, int numOfHospitals,
String nameHospital, String nameDirector) {
Hospital h1 = new Hospital();
this.nameDirector=nameDirector;
this.nameHospital=nameHospital;
this.hospitalSchedule = new String[numOfAppointments];
for (int i=0; i < numOfAppointments; i++) {
hospitalSchedule[i] = "open";
}
return h1;
}
}
Main Class
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Inputting #vendors, #hospitals
int vendorCounter=1;
System.out.println("Enter the total number of appointment slots.");
Scanner myScanner = new Scanner(System.in);
int numOfAppointments = Integer.parseInt(myScanner.nextLine());
System.out.println("Enter the total number of hospitals in the draft.");
int numOfHospitals = Integer.parseInt(myScanner.nextLine());
ArrayList<Hospital> hospitals = new ArrayList<Hospital>();
//creating hospitals
int hospitalCounter = 1;
while (hospitalCounter <=numOfHospitals) {
System.out.println("Enter the name of hospital #" + hospitalCounter);
String currentHospitalName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
System.out.println("Enter the director's name for " + currentHospitalName + ".");
String currentDirectorName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
Hospital h1 = new Hospital();
h1.createNewHospital(numOfAppointments, numOfHospitals, currentHospitalName, currentDirectorName);
hospitals.add(h1);
hospitalCounter++;
}
//creating vendors
ArrayList<Vendor> vendors = new ArrayList<Vendor>();
Scanner myInput = new Scanner(System.in);
while (vendorCounter != 2000){
System.out.println("Are you entering a new vendor? Enter Yes or No");
String isAddingNewVendor;
isAddingNewVendor= myScanner.nextLine();
if (isAddingNewVendor.equalsIgnoreCase("yes"))
{
System.out.println("Enter the name of the salesperson.");
String salespersonName = myInput.nextLine();
System.out.println("Enter the company name for "+salespersonName+".");
String vendorCompanyName = myInput.nextLine();
Vendor v1 = new Vendor();
v1.createNewVendor(vendorCounter, numOfAppointments, numOfHospitals,salespersonName,vendorCompanyName);
vendors.add(v1);
vendorCounter++;
}
else vendorCounter = 2000;
}
/* System.out.println(vendors.get(0).vendorCompanyName);
System.out.println(hospitals.get(0).nameHospital);
System.out.println(vendors.get(0));
vendors.get(0).printVendorSchedule();
vendors.get(0).printVendorPicks();
hospitals.get(0).printHospitalSchedule();
if (vendors.get(0).checkVendorSchedule(0)) {
System.out.println ("This appointment slot is open for the vendor.");
}
if (hospitals.get(0).checkHospitalSchedule(0)) {
System.out.println("This appointment slot is open for the hospital.");
}*/
for (int i = 0; i < numOfHospitals; i++) {
System.out.println("Information for hospital #" + i);
System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
System.out.println("Director's name: " + hospitals.get(i).nameDirector);
System.out.println("The hospital's initial schedule:");
hospitals.get(i).printHospitalSchedule();
}
for (int i = 0; i < vendors.size(); i++) {
System.out.println("Information for vendor #" + i);
System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
System.out.println("The vendor's hospital choices:");
vendors.get(i).printVendorPicks();
System.out.println("The vendor's initial schedule:");
vendors.get(i).printVendorSchedule();
}
//draft loop logic
int draftRound = 1;
while (draftRound <= numOfAppointments) {
if (draftRound % 2 == 1) {
//insert code for odd-numbered draft rounds here.
//these rounds should start with picker 1, then 2, 3, etc.
int currentVendor = 0; //starts this round with the first vendor
while (currentVendor < vendors.size()){
//this while loop continues running through a single draft round until all vendors get a pick
int currentAppointmentSlot = 0;
int currentVendorPickSlot=0;
while (currentVendorPickSlot < numOfHospitals) { //this loops through a single vendor until all appointments checked or appt assigned
//check if hospital and vendor are both open
String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
System.out.println(currentHospital);
int currentHospitalsIndex = hospitals.indexOf(currentHospital); //indexof is returning -1 creating the exceptionoutofbounds
System.out.println("Current hospital index:"+ currentHospitalsIndex);
if ( hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
currentAppointmentSlot++;
}
else {
vendors.get(currentVendor).setVendorAppointment(currentVendorPickSlot, hospitals.get(currentHospitalsIndex).nameHospital);
hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentVendorPickSlot, vendors.get(currentVendor).salespersonName);
break; // does this break the loop?
}
}
currentVendor++;
}
draftRound++;
}
if (draftRound % 2 == 0) {
//insert code for even-numbered draft rounds here.
//these rounds should start with the last picker and go down by 1 each turn until 1st picker.
int currentVendor = vendors.size()-1; //starts this draft round with the last vendor
while (currentVendor >= 0) {
//this while loop continues running through a single draft round until all vendors get a pick
int currentAppointmentSlot = 0; //looping through the hospital choices for a single vendor
int currentVendorPickSlot=0;
while (currentVendorPickSlot < numOfHospitals) {
//check if hospital and vendor are both open
String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
int currentHospitalsIndex = hospitals.indexOf(currentHospital);
if (hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
currentAppointmentSlot++;
//continuing the loop if the appointment slot doesn't work
}
else {
vendors.get(currentVendor).setVendorAppointment(currentAppointmentSlot, hospitals.get(currentHospitalsIndex).nameHospital);
hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentAppointmentSlot, vendors.get(currentVendor).salespersonName);
currentVendor++;
break; // does this break the loop?
}
}
currentVendor++;
}
draftRound++;
}
else break;
}
for (int i = 0; i < numOfHospitals; i++) {
System.out.println("Information for hospital #" + i);
System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
System.out.println("Director's name: " + hospitals.get(i).nameDirector);
System.out.println("The hospital's final schedule:");
hospitals.get(i).printHospitalSchedule();
}
for (int i = 0; i < vendors.size(); i++) {
System.out.println("Information for vendor #" + i);
System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
System.out.println("The vendor's final schedule:");
vendors.get(i).printVendorSchedule();
}
}}
First using stream we will Iterate through hospitals list,
find out the hospital from the list whose name equals currentHospital name, take out the first result using findFirst.
Since the result may be or may not be available it returns Optional.
So on Optional, we will say if it's (the hospital object which we were looking for) present we will get the hospital out of it using the get method
Optional<Hospital> result = hospitals.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();
if(result.isPresent()){
Hospital hospital = result.get();
}
I'm trying to make a program in java that you can add people's birthdays, names, birthmonths, and birthyears. I'm having a hard time trying to come up with the code to remove an object from the arraylist here is the following code. How would I go about writing the removePerson method?
import java.util.ArrayList;
public class Analyzer {
// instance variables - replace the example below with your own
private final static int DAYS_PER_MONTH = 31;
private final static int MONTHS_PER_YEAR = 12;
private int[] birthDayStats;
private int[] birthMonthStats;
private ArrayList<Person> people;
/**
* Constructor for objects of class Analyzer
*/
public Analyzer() {
this.people = new ArrayList<Person>();
this.birthDayStats = new int[Analyzer.DAYS_PER_MONTH];
this.birthMonthStats = new int[Analyzer.MONTHS_PER_YEAR];
}
public void addPerson(String name, int birthDay, int birthMonth, int
birthYear) {
Person person = new Person(name, birthDay, birthMonth, birthYear);
if (person.getBirthDay() != -1 || person.getBirthMonth() != -1) {
people.add(person);
birthMonthStats[birthMonth - 1]++;
birthDayStats[birthDay - 1]++;
} else {
System.out.println("Your current Birthday is " + birthDay + " or "
+ birthMonth + " which is not a correct number 1-31 or 1-12 please " +
"put in a correct number ");
}
}
public void printPeople() { //prints all people in form: “ Name: Tom Month: 5 Day: 2 Year: 1965”
int index = 0;
while (index < people.size()) {
Person person = (Person) people.get(index);
System.out.println(person);
index++;
}
}
public void printMonthList() { //prints the number of people born in each month
// Sample output to the right with days being similar
int index = 0;
while (index < birthMonthStats.length) {
System.out.println("Month number " + (index + 1) + " has " +
birthMonthStats[index] + " people");
index++;
}
}
public Person removePerson(String name) {// removes the person from the arrayList
}
}
/**
* Removes the {#code Person} with the given {#code name} from the list
* #param name the {#code Person}'s name
* #return the {#code Person} removed from the list or {#code null} if not found
*/
public Person removePerson(String name) {
if (name != null) {
for (Iterator<Person> iter = people.iterator(); iter.hasNext(); ) {
Person person = iter.next();
if (name.equalsIgnoreCase(person.getName())) {
iter.remove();
return person;
}
}
}
return null;
}
See the java.util.Iterator#remove() method.
Tuesday learning bonus:
If you want to look for a name faster in your list, you should consider to use a java.util.Map implementation:
HashMap<String,Person> people;
You can add Person objects in a smart way in order to make your search case insensitive:
people.put(name.toLowerCase(), new Person(name, ...));
... and your removePerson method become:
public Person removePerson(String name) {
if (name != null)
name = name.toLowerCase();
return people.remove(name);
}
See the java.util.Map#remove() method.
If you are using Java 1.8. It's pretty simple way to do. This will remove Person having 'name' from your list.
people.removeIf(x -> name.equalsIgnoreCase(x.getName()));
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