Java method for checking whether an element of an array exists - java

I have two classes called Ticket and Register. Register is a class that takes in a ticket array. A ticket contains a time and a string with its Ticket ID. One of the methods in my Register Class is called contains() and it returns a Boolean. It checks whether the register contains a ticket with that ID. My problem is that it only shows true for the first ticket element and false for all the others even if it contains the ticket, therefore I believe the problem is with my contains() function. I am very knew to Java so if someone could help me it would be greatly appreciated. Here is my code for Register and my driver code.
/
// This is class called Register that has the methods:"add()","contains()","retrieve()" and the constructor "Register()"
public class Register{
public Ticket[] tickets;
public int numTickets;
public Register(){
tickets = new Ticket[100];
numTickets = 0;
}
public void add(Ticket ticket){ //add ticket method. Takes a ticket as a parameter and adds it to the array
tickets[numTickets] = ticket;
numTickets = numTickets+1; // incramenting array
}
public boolean contains(String ticketID){ //contains method. Takes a string from the ticket using the ID() method and uses as a parameter.
boolean b = false;
for (int i = 0;i<100;i++){
if (ticketID.equals(tickets[i].ID())){ // checks to see if ticket ID is in the array
b = true; // return value is true if found
break;
}
break;
}
return b; // returns true of false
}
public Ticket retrieve(String ticketID){ // returns the ticket with the specified ID
int j = 0; // initializing return value
for (int i = 0;i<100;i++){
if (ticketID.equals(tickets[i].ID())){
j = i;
break;
}
}
return tickets[j]; // returns ticket
}
}
Here is my driver code
public static void main(String[] args){
Register r = new Register();
Ticket t;
t = new Ticket(new Time("13:00"), "00001");
String ID_One = t.ID();
r.add(t);
t = new Ticket(new Time("13:18"), "00002");
String ID_Two = t.ID();
r.add(t);
System.out.println(r.contains(ID_One));
System.out.println(r.contains("00002"));
System.out.println(r.retrieve(ID_Two).toString());
Output is:
true
false // this should be true
Ticket[id=00002, time=13:18:00]

Delete the second break, which always exits the for loop on the first iteration, so only the first element of the array is ever compared.
You could simplify your code to 1 line:
public boolean contains(String ticketID) {
return Arrays.stream(tickets).map(Ticket::ID).anyMatch(ticketID::equals);
}

You're using a break statement outside your if condition, so it will only check the first element then break the loop. You can see this immediately with better formatting.
for (int i = 0; i<100; i++){
if (ticketID.equals(tickets[i].ID())){ // checks to see if ticket ID is in the array
b = true; // return value is true if found
break;
}
break;
}
Remove the second break to fix this so you only break when your if condition is true.
For personal advise, you might want to consider using a Map structure if you have a unique ID for each ticket. This can reduce your search time considerably.
int numTickets = 0;
Map<String, Ticket> ticketMap = new HashMap<>();
public void add(Ticket ticket) {
numTickets++;
ticketMap.put(ticket.ID(), ticket);
}
public boolean contains(String ticketId) {
return ticketMap.containsKey(ticketId);
}
public Ticket retrieve(String ticketId) {
return ticketMap.get(ticketId);
}

Related

Java ArrayList add class object to list if object name is not already in the list?

I have looked through other questions but cant seem to find the answer I am looking for.
I am having trouble figuring out how to create a loop that adds a class object to an ArrayList only if it its name is not used in the list already.
This is the class I have.
package myPackage;
public class Cube {
private int length;
private String name;
public Cube(int initLength, String initName) {
this.length = initLength;
this.name = initName;
}
I would like to create new cubes and add them to a list. Here is the code I am trying to do this with.
In the while loop I can't figure out how to determine if the name has been used or not
package myPackage;
import java.util.ArrayList;
import java.util.Scanner;
public class PartFive {
public static void main(String[] args) {
ArrayList<Cube> cubelist = new ArrayList<>();
Cube oshea = new Cube (13, "oshea");
Cube mike = new Cube (7, "tony");
cubelist.add(oshea);
cubelist.add(mike);
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("enter cube name (blank quits): ");
String name = reader.nextLine();
if (name.equals("")){
break;
}
System.out.println("enter side length: ");
int length = Integer.valueOf(reader.nextLine());
Cube newcube = new Cube(length, name);
if(cubelist.contains(newcube.name)) {
// dont add to list
}
else {
cubelist.add(newcube);
}
}
reader.close();
System.out.println(cubelist);
}
}
Any constructive criticisms and suggestions are welcomed.
Replace
if(cubelist.contains(newcube.name)) {
dont add to list
}
else {
cubelist.add(newcube);
}
with
boolean found = false;
for(Cube cube: cubelist){
if(cube.getName().equals(name)) {
found = true;
break;
}
}
if(!found) {
cubelist.add(newcube);
}
The idea is to use a boolean variable to track if a cube with the same name as that of the input name already exists in the list. For this, iterate cubelist and if a cube with the same name as that of the input name is found, change the state of the boolean variable and break the loop. If the state of the boolean variable does not change throughout the loop, add the cube to the list.
From the code in your question:
if(cubelist.contains(newcube.name)) {
// don't add to list
}
else {
cubelist.add(newcube);
}
Method contains in class java.utilArrayList is the way to go but you need to be aware that method contains [eventually] calls method equals of its element type. In your case, the element type is Cube. Therefore you need to add a equals method to class Cube. I don't know what determines whether two Cube objects are equal, but I'll guess, according to your question, that they are equal if they have the same name, even when they have different lengths. I will further assume that name cannot be null. Based on those assumptions, here is a equals method. You should add this method to class Cube.
public boolean equals(Object obj) {
boolean areEqual = false;
if (this == obj) {
areEqual = true;
}
else {
if (obj instanceof Cube) {
Cube other = (Cube) obj;
areEqual = name.equals(other.name);
}
}
return areEqual;
}
Now, in method main of class PartFive you can use the following if to add a Cube to the list.
if (!cubelist.contains(newcube)) {
cubelist.add(newcube);
}
You can check for duplicate names in the cubelist array using lambda expressions (for better readability):
boolean isNameAlreadyExisting = cubelist.stream()
.anyMatch(cube -> cube.getName().equals(newcube.getName())); // this is returning true if any of the cubelist element's name is equal with the newcube's name, meaning that the name is already existing in the cubelist
if (!isNameAlreadyExisting) {
cubelist.add(newcube);
}
One thing that you should do is to remove the while(true) instruction which causes an infinite loop.
Another suggestion is to display the name of objects contained by cubelist, to see that indeed the names are not duplicated:
cubelist.stream()
.map(Cube::getName)
.forEach(System.out::println);

How can I compare all the values of an enum with a given array in java?

I have an enum class with values:
enum carBrand{BMW,HONDA,MERC,AUDI};
And there's an array called Sales with Array values:
sales[] = {CHEVVY, BMW , MERC, AUDI};
So how could I check that the sales[] has all the values of enum carBrand?
I'm trying to put it in a for loop as:
for(int i = 0; i<sales.length;i++){
if(carBrand.sales == sales[i]){
return true;
}
return false;
}
Add carBrand values to list
loop sales, remove the carBrand from the list
check if list is empty, if so they have all the values
Note: Class names should be names in PascalCase (CarBrand, Sales)
I would, personally, suggest using a list object rather than an Array where you are using such, however, this should work.
public static boolean checkArray(carBrand[] array) {
for (carBrand c : carBrand.values()) {
boolean found = false;
for (carBrand a : array) {
if (a == c) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
where the "array" parameter would be invoked as the sales object in your code.
This code will return false if not every enum value exists within your array.
Off-topic:
Things like this are actually all over the internet - here, google, even Bing (as garbo as Bing is), so searching before requesting help, probably a viable choice
public class Enumeration {
enum carBrand{BMW,HONDA,MERC,AUDI};
public static void main(String[] args) {
String sales[] = {"CHEVVY", "BMW" , "MERC", "AUDI"};
for(carBrand brand:carBrand.values()) {
boolean bran=false;
for(int i=0;i<sales.length;i++) {
if(brand.toString()==sales[i]) {
bran=true;
break;
}
}
if(!bran==true) {
System.out.println("Sales doesn't have " +brand);
}
}
}
}

Fundamental misunderstanding of objects and attributes in Java

I'm sitting on an assignment for university and I'm at a point, where I fear I haven't really understood something fundamental in the concecpt of Java or OOP altogether. I'll try to make it as short as possible (maybe it's sufficient to just look at the 3rd code segment, but I just wanted to make sure, I included enough detail). I am to write a little employee management. One class within this project is the employeeManagement itself and this class should possess a method for sorting employees by first letter via bubblesort.
I have written 3 classes for this: The first one is "Employee", which contains a name and an ID (a running number) , getter and setter methods and one method for checking whether the first letter of one employee is smaller (lower in the alphabet) than the other. It looks like this:
static boolean isSmaller(Employee source, Employee target) {
char[] sourceArray = new char[source.name.length()];
char[] targetArray = new char[target.name.length()];
sourceArray = source.name.toCharArray();
targetArray = target.name.toCharArray();
if(sourceArray[0] < targetArray[0])
return true;
else
return false;
}
I tested it and it seems to work for my case. Now there's another class called EmployeeList and it manages the employees via an array of employees ("Employee" objects). The size of this array is determined via constructor. My code looks like this:
public class EmployeeList {
/*attributes*/
private int size;
private Employee[] employeeArray;
/* constructor */
public EmployeeList(int size) {
this.employeeArray = new Employee[size];
}
/* methods */
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
/* adds employee to end of the list. Returns false, if list is too small */
boolean add(Employee m) {
int id = m.getID();
if (id > employeeArray.length) {
return false;
} else {
employeeArray[id] = m;
return true;
}
}
/* returns employee at certain position */
Employee get(int index) {
return employeeArray[index];
}
/* Sets employee at certain position. Returns null, if position doesn't exist. Else returns old value. */
Employee set(int index, Employee m) {
if (employeeArray[index] == null) {
return null;
} else {
Employee before = employeeArray[index];
employeeArray[index] = m;
return before;
}
}
Now comes my real problem: In a third class called "employeeManagement" I am supposed to implement the sorting algorithm. The class looks like this:
public class EmployeeManagement {
private EmployeeList ml = new EmployeeList(3);
public boolean addEmployee(Employee e) {
return ml.add(e);
}
public void sortEmployee() {
System.out.println(ml.getSize()); // I wrote this for debugging, exactly here lies my problem
for (int n = ml.getSize(); n > 1; n--) {
for (int i = 0; i < n - 1; i++) {
if (Employee.isSmaller(ml.get(i), ml.get(i + 1)) == false) {
Employee old = ml.set(i, ml.get(i + 1));
ml.set(i+1, old);
}
}
}
}
The "println" before my comment returns "0" in console... I am expecting "3" as this is the size I gave the "EmployeeList" as parameter of the constructor within my "EmployeeManagement" class. Where is my mistake ? And how can I access the size of the object I created in the "EmployeeManagement" class (the "3") ? I'm really looking forward to your answers!
Thanks,
Phreneticus
You are not storing size in your constructor. Something like,
public EmployeeList(int size) {
this.employeeArray = new Employee[size];
this.size = size; // <-- add this.
}
Also, setSize isn't going to automatically copy (and grow) the array. You will need to copy the array, because Java arrays have a fixed length. Finally, you don't really need size here since employeeArray has a length.
The size variable you are calling is the class field. If you take a quick look at your code, the getter is getting the field (which is initialized as zero when created). The size you are using it. The good way of doing it would be to get the size of the array in the getter like this:
public int getSize() {
return employeeArray.length;
}
This would return the size of the array in the object.

Suspicious call to Collection.contains method in ArrayList

I am getting a warning that watchStore.contains(s) is a suspicious call to java.util.Collection#contains. How can I fix it? I want to use contains() to find a particular object with the matching serial number.
public Watch findWatchBySerialNumber(long srch) {
long s = srch;
Watch watch = null;
for(int i = 0; i < watchStore.size(); i++) {
watch = watchStore.get(i);
if(watchStore.contains(s)) {
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
Presuming that Watch is the class, watchStore is a List<Watch>, and that a field serialNo exists on Watch...
public Optional<Watch> findWatchBySerialNumber(long serial) {
return watchStore.stream()
.filter(w -> w.getSerialNo() == serial)
.findFirst();
}
If you're not using Java 8, the code is close, but a bit more dangerous since you have the chance to return null. If you can use Guava's Optional, that'd be a better choice here.
public Watch findWatchBySerialNumber(long serial) {
for(Watch w : watchStore) {
if(w.getSerialNo() == serial) {
return w;
}
}
return null;
}
Your contains isn't going to work since your list doesn't contain Longs, it contains Watchs. This is also why the compiler sees it as dubious; contains accepts an Object but it will return false if what you're looking for doesn't have a comparable equals for what's in your list.
You have to iterate over the entirety of your collection to find it in this scenario, especially since you're looking for a specific property on those objects as opposed to a specific, easy-to-provide value.
please how can I fix that. I want to use the contain() to find a
particular object with the matching serial number.
In that case override Watch's equals() to use serialNumber field for comparison.
Then add constructor that accepts serialNumber.
public class Watch {
private final long serialNumber;
public Watch(long serialNumber) {
this.serialNumber = serialNumber;
}
#Override
public boolean equals(Object obj) {
return obj == this ||
(obj instanceof Watch && ((Watch)obj).serialNumber == serialNumber);
}
#Override
public int hashCode() {
return (int)serialNumber;
}
}
Replace if(watchStore.contains(s)){ with if(watchStore.contains(watchToFind)){ where Watch watchToFind = new Watch(s);
you can use contains method from org.apache.commons.lang.ArrayUtils package.
Checks if the value is in the given array.
The method returns false if a null array is passed in.
Parameters:
array the array to search through
valueToFind the value to find
Returns:
true if the array contains the object
long [] imageHashes= {12l,13l,14l,15l};
System.out.println(ArrayUtils.contains(imageHashes, 13l));

Reference a method within a method in java?

Ok, so I am going to see if this makes sense. In the second method below (int numAdd) I want to be used for the private method (int searchingNum). I don't really understand how private methods work, but whatever number the user enters for the (int numAdd) I want to be duplicated for the parameters in the first method. How is this possible?
//See if user input returns -1 to test whether or not number exists in the array
private int indexOf(int searchingNum)
{
}
//Add number in the array
public boolean addNumber(int numAdd)
{
if (list.contains(numAdd))
{
return false;
}
else
{
list.add(numAdd);
count++;
return true;
}
}
that's it? indexOf(numAdd);
public boolean addNumber(int numAdd)
{
// somewhere, in the middle of nowhere
indexOf(numAdd);
// more of code
}
You can call method of same class directly. No need to do anything. Like this :
public boolean addNumber(int numAdd)
{
int abc = indexOf(numAdd);
//Whatever you want to do...
}

Categories

Resources