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];
}
}
Related
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);
}
}
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();
}
First off I know this probably isn't the most sophisticated way to do what I want, but its the way I thought of.
I am attempting to load in Soccer/Football data into an array list then create commands to let me analyze it.
Like if I want to know the last couple fo scores between two teams, or how many goals a team has scored in some seasons.
I have a file (6.txt) with my data delimited by ,
Ex. "12/8/17","Alaves","Las Palmas",2,0,'H',22,6,9,1
I have a contractor that takes in arguments
Then I have an array list for each team with their data
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class games {
String hTeam;
String date;
String aTeam;
int totGoals;
int hGoals, aGoals, result, points, wins, draws, losses, hShots, aShots, hShotsTarget, aShotsTarget;
public games(String date, String hTeam, String aTeam, int hGoals, int aGoals, char result, int hShots, int aShots, int hShotsTarget, int aShotsTarget) {
this.hTeam = hTeam;
this.aTeam = aTeam;
this.hGoals = hGoals;
this.aGoals = aGoals;
this.result = result;
this.hShots = hShots;
this.aShots = aShots;
this.date = date;
}
public String toString() {
String temp = "";
String result = "";
if (this.result == 'H') {
result += "won against";
}
else if(this.result == 'A') {
result += "lost to";
}
else if (this.result == 'D') {
result += "drew with";
}
temp += "On " + date + " " + hTeam + " " + result + " " + aTeam + " " + hGoals + " to " + aGoals + "\n";
return temp;
}
public static void main(String[] args) {
ArrayList<games> Alaves = new ArrayList<games>();
Scanner s = new Scanner(new File("6.txt"));
while (s.hasNext()) {
Alaves.add(new games(s.nextLine()));
}
}
}
I want to be able to create an array list for each team with an associated file that will fill that list.
My end goal, is to be able to compare two teams using this data, which team is more likely to win, well lets check head to head matches and goals scored etc.
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++;
}
}
}
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