I'm having some trouble with one of my methods. A brief overview of what my method is supposed to do. Here's what I have so far.
public boolean addGame(String team1, String team2) {
boolean result;
if (team1.equals(team2))
result = false;
}
if (a game between two parameter teams has previously been added by
earlier call to addGame){
result = false;
}
else {
result = true;
}
I want my method to return false if a game between two parameter teams has previously been added to the conference object by an earlier call to addGame and
if the name of team1 and team2 are the same name.
My issue is the syntax for what's inside of my second if statement. Not sure how to go about it.
Thanks in advance for all the help.
Depends on how long you plan on saving the information. If it is just in the runtime, you can do something such as saving the two teams to an array.
If you want to save it for a longer time, you need some way of persisting the information, possibly a table in a database?
Then, you can query to data and check if the combination existed already.
You can create a history of the added teams:
ArrayList<String> history = new ArrayList<String>();
//As you add the teams
history.add(teamName); //add to history as well
//To check if teams already exist or added before
if(history.contains(team1) || history.contains(team2)){
return false;
}
If you have an ArrayList called games, and the games are stored in the format "team1;team2", then you can do games.indexOf(team1 + ";" + team2) == -1 for the if statement.
Related
My task is:
The program should read items from the user. When all the items from the user have been read, the program prints the information of each item.
For each item, its identifier and name should be read. If the identifier or name is empty, the program stops asking for input, and prints all the item information. Modify the program so that after entering the items, each item is printed at most once. Two items should be considered the same if their identifiers are the same (there can be variation in their names in different countries, for instance).
If the user enters the same item multiple times, the print uses the item that was added first.
I have done the code below, but it will still add items with the same identifier.
Why? How can I fix it?
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> itemsName = new ArrayList();
ArrayList<String> itemsIdentifier = new ArrayList();
while(true){
System.out.println("Identifier? (emppty will stop)");
String identifier = scanner.nextLine();
if( identifier.isEmpty()){
break;
}
System.out.println("Name? (emppty will stop");
String name = scanner.nextLine();
if(name.isEmpty()){
break;
}
if(!(itemsIdentifier.contains(identifier))){
itemsIdentifier.add(identifier);
}
if(!(itemsName.contains(name))){
itemsName.add(name);
}
}
System.out.println("==Items==");
int j = 0;
for(String i: itemsIdentifier){
System.out.println(i + ": "+ itemsName.get(j));
j++;
}
}
}
I think the problem with your code is that you are adding name into itemsName list even when you are not adding identifier into itemsIdentifier list in the following lines
if(!(itemsIdentifier.contains(identifier))){
itemsIdentifier.add(identifier);
}
if(!(itemsName.contains(name))){
itemsName.add(name);
}
Ideally shouldn't you either add both name and identifier or don't add any?
You have a while(true) loop which will keep going indefinitely, you are breaking the loop only if the user input is empty, but you are not doing anything when the lists already contain an identifier more than once. (You are adding to the list if you have a unique identifier).
EDIT
I have other misgivings on the code above (I am assuming that this is an assignment), but since I do not know if you built this on top of what the lecturer gave you, I can only speculate. Some thoughts on the code above:
You could create your own Record object.
As per the instructions, you would need to override the equals method.
Instead of having two lists, you would have only 1 list of type Record.
Try something like this:
if(!(itemsIdentifier.contains(identifier))) {
itemsIdentifier.add(identifier);
itemsName.add(name);
}
In your code, if the id is already in the list, the name could still be added...
You only need to check whether the identifier is similar or not. The name similarity condition is not required. As long as the identifiers are different( though they have the same name), you still add them to the itemsIdentifier and itemsName. On the other hand, if the identifiers are identical, there is no need to run a check on the similarity of the name.
I wrote a method addAppointmentSaveButtonClicked that creates an object like this:
Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);
Then it adds that object to observableArrayList like this:
MainScreenController.appointmentDisplayList.add(newAppointment);
Now when I want to create a new Appointment or Edit existing one, I want to check whether there is already one with the same starting time in appointmentDisplayList array.
StartDateTime is LocalDateTime variable that is chosen from a combobox menu and always formatted like this:2020-02-15 10:30:00 in 30 minute intervals and there is no problems with milliseconds or anything like that.
What I have done so far:
I created following method that iterates through appointmentDisplayList like this:
public static boolean existingAppointment(LocalDateTime ldt) {
for (Appointment app : appointmentDisplayList) {
if (app.getStart() == ldt) {
System.out.println("True");
return true;
}
}
System.out.println("False");
return false;
}
Then whenever save button is clicked, I put in object creation code inside the IF code block like this:
if(!existingAppointment(startDateTime)) {
AppointmentMethods.addAppointment(appointmentType, chosenCustomerId, utcStartTime, utcEndTime);
appointmentId = AppointmentMethods.getAppointment(chosenCustomerId, utcStartTime).getAppointmentId();
Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);
MainScreenController.appointmentDisplayList.add(newAppointment);}
Now the problem I am having with my code is that every single time and date I choose for my new appointent, this if block always comes as false, and duplicate appointments are added to my ArrayList.
I hope any experienced coder can help me figure out what I am doing wrong here? Thank you in advance!
For objects, == tests if they are the same object. Assuming it has been set up well, .equals() tests if they have the same value. For a good discussion of setting up .equals, see nice overview of overriding equals, including visualization of this issue
That is why you needed app.getStart().equals(ldt) to compare the date values, to see if both objects represented the same date. app.getStart() == ldt was checking if they were the same object, which is not what you wanted.
Pardon me as I'm quite a beginner in coding. I have tried researching for ways to add some missing record into the lists but still can't seem to fit it correctly into my code.
I have two ArrayLists with different resultsets. Say, the first one is derived in other method and stored in abcList. This list is then used in my current fixChartStats method as a param.
In my code, I will check for the corresponding record in abcList with the second list I derive from the hql query in fixChartStats method.
If the record corresponds, then I'll do the necessary action as shown below to update the ApprovedCount number etc, else i set it to 0.
How do I go about adding the records that are missing in second list I got into the first arraylist (i.e. abcList)? Can anyone here shed some light? Do let me know if my questions are unclear. Thanks in advance, guys!
private void fixChartStats(List<TAbcModel> abcList, Map<String, Object> param, List<IssueModel> issueList, List<DestModel> destList) throws Exception {
//initialize the hql query
//translate all fields from Object[] into individual variable
firstRow = true;
for (TAbcModel abc : abcList) {
if (abc.getId().getAbcYear() = abcYear &&
abc.getId().getAbcMonthId() = abcMonthId &&
abc.getId().getAbcApplAccnId().getAccnId().equalsIgnoreCase(abcApplAccnId.getAccnId()) {
if (firstRow) {
abc.setApprovedCount(abcApprovedCount);
abc.setCancelledCount(abcCancelledCount);
firstRow = false;
} else {
abc.setApprovedCount(0);
abc.setCancelledCount(0);
}
}else{
// How to do the necessary here
// Below is what I've tried
abcList.add(abc);
}
}
}
When I debug, I noticed that it was added into the list. But soon after it was added, ConcurrentModificationException was thrown.
Create a local list and add missing records to it then add all elements from the local list to the abcList
List<TAbcModel> temp = new ArrayList<>();
in your loop:
} else {
temp.add(abc);
}
after loop
abcList.addAll(temp);
I'm trying to find if multiple HashMaps are empty.
To give some context. I have a hashmap declared here.
static Map<Integer, College> tblColleges = new HashMap<Integer, College>();
For each college object:
Map<Integer, Department> tblDepartments = new HashMap<Integer, Department>();
I'm trying to add a major. Majors can only exist as an attribute of Department.
Here's what I have right now.
int numberofColleges = Databases.tblColleges.size();
int emptyColleges = 0;
for(int key: Databases.tblColleges.keySet()) {
if(Databases.getTblColleges(key).tblDepartments.isEmpty()) {
emptyColleges++;
}
}
if(numberofColleges == emptyColleges) {
System.out.println("Invalid. Requires at least 1 department.");
}
I should only be able to create a Major if at least 1 college has a department.
Essentially for each college object that exists in the tblColleges, I'm checking to see if it's department hashmap is empty. If it is empty, then I increment the number of empty colleges.
Afterward, I compare the number of college objects with empty college objects found, if they are equal then I print an error.
I was wondering if there was a better more efficient way to do this, maybe with some function that exists that I'm not familiar with rather than using variables.
Q: Can you do the check "more efficiently"?
A: You could optimize it a bit:
boolean nonEmptyColleges = false;
for (int key: Databases.tblColleges.keySet()) {
if (!Databases.getTblColleges(key).tblDepartments.isEmpty()) {
nonEmptyColleges = true;
break;
}
}
The above short circuits as soon as it finds a College with a Department. That will be a substantial improvement in a lot of cases.
Then, assuming that Databases.tblColleges is a Map:
boolean nonEmptyColleges = false;
for (int college: Databases.tblColleges.values()) {
if (!college.tblDepartments.isEmpty()) {
nonEmptyColleges = true;
break;
}
}
Q: Can you do the check with less code?
A: Using Java 8 streams you could write the last as:
boolean nonEmptyColleges = Databases.tblColleges.values().stream()
.anyMatch(c -> !c.tblDepartments.isEmpty());
(I think ...)
Q: But is this the right approach?
A: IMO, no.
It seems that you intend to do this check each time you add a major. That's not necessary.
Majors can only exist as an attribute of Department.
The key thing that you need to check is that the Department you want to add the major for exists.
If the Department doesn't exist you can't add the major to it.
If the Department does exist you can the major to it, whether or not it is currently a department of a college1.
The bigger point here is that any data model is going to have a variety of data integrity rules / constraints on it. But that does mean that you need to explicitly check all of them each time the model is changed. You only need to check the preconditions for the change (e.g. that the Department exists) and any constraints that could be invalidated by the change.
1 - The "not" case assumes that there may be some other way of finding a Department. It could be a separate table of Department objects, or it could be that you are in the process of creating and building a new Department and haven't added it to its College yet.
I have an array list in a class the array is called realtorList. From my main class I store objects with realtor data to the realtorList.
My data that is stored to a text file and is read in the first line.
This is the first element in the realtorList after I store the first line of data.
[Realtor{licenseNumber=AA1111111, firstName=Anna, lastName=Astrid, phoneNumber=111-111-1111,
commission=0.011}]
When I read the next line of data from the input file I need to see if the licenseNumber in bold already exists in the realtorList. I am having trouble figuring out how to go about doing this.
For example if the next realtor data license number is AA1111111 how do I check the realtorList for AA1111111 which does exist for this example.
A really simple way to do this would be to have a String ArrayList running alongside (for example, one called licenses) and use an if statement with indexOf to return if that license value is already in the List. Since the licenses ArrayList only has one value it can be easily searched with indexOf.
An example would be
private boolean checkLicense (String licenseNumber) {
int i = licenses.indexOf(licenseNumber);
if(i == -1) {
return false;
} else {
return true;
}
}
Similar code works in one of my projects where a dynamic List of motors for a robot checks to see if there's already a motor with the listed port before adding a new one.
Another method could use a for loop for a linear search such as
private boolean checkLicense (String licenseNumber) {
for(int i = 0; i < (realtorList.size() - 1); i++) {
if (licenseNumber.equals(realtorList[i].getLicenseNumber())) {
return true;
}
}
return false;
}
This would perform a linear search of each and every object until it finds it (it would need to be in a method like the one for the example above to work this way)