How to create a Junit test for the below code - java

I am able to get the coverage for the second and the third condition but not able to get the coverage for the last and the first one.
#Override public boolean equals(Object obj)
{
if(this == obj) {
return true;
}
if(obj == null)
{
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
Rating other = (Rating) obj;
boolean bool= score == other.score ;
boolean bool2=Objects.equals(user, other.user);
return bool&&bool2;
}
the below one is my test function
public void equalsTest_lastcondition() {
Rating test=new Rating();
Object obj2=testwa2;
Rating other = (Rating) obj2;
boolean bool=false;
if(other.getScore()==testwa1.getScore())
{ bool=true;}
boolean bool2 =Objects.equals(test.getUser(), other.getUser());
assertEquals(true, bool && bool2);
}

this == obj is simple test.equals(test)
getClass() != obj.getClass() is test.equals("").
PS: You can use any object instead of String there.

#Test
void equalsTest() {
String score = 1;
String user = "user";
Rating rating = new Rating(score, user);
assertTrue(rating.equals(rating)); // 1. if statement
assertFalse(rating.equals(null)); // 2. if statement
assertFalse(rating.equals(score)); // 3. if statement
assertTrue(rating.equals(new Rating(score, user))); // other statements
}
Updated:
String score = 1;
String user = "user";
Rating rating = new Rating(score, user);
#Test
void equalsShouldReturnTrueWhenComparingTheSameInstance() {
assertTrue(rating.equals(rating)); // 1. if statement
}
#Test
void equalsShouldReturnFalseWhenComparingTheNullValue() {
assertFalse(rating.equals(null)); // 2. if statement
}
#Test
void equalsShouldReturnFalseWhenComparingTheWrongType() {
assertFalse(rating.equals(score)); // 3. if statement
}
#Test
void equalsShouldReturnTrueWhenComparingNewInstanceWithSameValues() {
assertTrue(rating.equals(new Rating(score, user))); // other statements
}

Related

Java: Set.contains() gives wrong result

Since Set.contains(Object o) should just use equals to check if an object is in a Set, how can the following two methods produce different results? In my project, method 1 does not throw an exception, but method 2 does throw an exception.
For information, the object "group" is in the set "groups", so Method 1 works like I would expect it.
boolean java.util.Set.contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
Method 1:
boolean ex = true;
for (AccessControlGroup acg : groups) {
if ((acg.equals(group))) {
ex = false;
}
}
if (ex) {
throw new IllegalStateException("Invalid group");
}
Method 2:
if (!(groups.contains(group))) {
throw new IllegalStateException("Invalid group");
}
Further information:
HashSet is used.
AccessControlGroup:
public List<AccessControlGroup> getInherits() {
if (this.inherits == null) {
this.inherits = new ArrayList<>();
}
return this.inherits;
}
public void setInherits(List<AccessControlGroup> inherits) {
this.inherits = inherits;
}
public List<AccessControlPermission> getPermissions() {
if (this.permissions == null) {
this.permissions = new ArrayList<>();
}
return this.permissions;
}
public void setPermissions(List<AccessControlPermission> permissions) {
this.permissions = permissions;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
// prevent infinity loops or other sick effects
// result = prime * result + ((this.inherits == null) ? 0 : this.inherits.hashCode());
result = prime * result + ((this.permissions == null) ? 0 : this.permissions.hashCode());
result = prime * result + ((this.type == null) ? 0 : this.type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AccessControlGroup other = (AccessControlGroup) obj;
// prevent infinity loops or other sick effects...
// if (!Objects.equal(this.inherits, other.inherits)) {
// return false;
// }
if (!Objects.equals(this.permissions, other.permissions)) {
return false;
}
if (!Objects.equals(this.type, other.type)) {
return false;
}
return true;
}
AccessControl:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AccessControl other = (AccessControl) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
I'll lay odds that you modified group after adding it to the set groups. That would change its hashCode, which would leave it in the wrong bucket in groups, which would mean contains would not find it anymore unless the new hashCode happened to collide with the old one.
Set< AccessControlGroups > groups = new HashSet<>();
AccessControlGroup group = new AccessControlGroup();
groups.add( group );
groups.contains( group ); // true
group.setPermissions( new ArrayList<>() );
groups.contains( group ); // false

How to write JUnit Test Case for ArrayList Object?

Here is my First Class AdminPostlCode. Contains some Strings and it's getters and Setters.
package org.sanket.zivameDataBase.adminPostalCode.model;
public class AdminPostalCode {
private String entity_id1;
private String postal_code1;
private String city1;
private String state1;
private String country1;
private String days_to_deliver1;
private String cod1;
private String pg1;
private String rpu1;
private String updated_by1;
private String updated_at1;
private String cod_couriername1;
private String pg_couriername1;
private String rto_couriername1;
public AdminPostalCode(){}
public AdminPostalCode(String entity_id1, String postal_code1,
String city1, String state1, String country1,
String days_to_deliver1, String cod1, String pg1, String rpu1,
String updated_by1, String updated_at1, String cod_couriername1,
String pg_couriername1, String rto_couriername1) {
super();
this.entity_id1 = entity_id1;
this.postal_code1 = postal_code1;
this.city1 = city1;
this.state1 = state1;
this.country1 = country1;
this.days_to_deliver1 = days_to_deliver1;
this.cod1 = cod1;
this.pg1 = pg1;
this.rpu1 = rpu1;
this.updated_by1 = updated_by1;
this.updated_at1 = updated_at1;
this.cod_couriername1 = cod_couriername1;
this.pg_couriername1 = pg_couriername1;
this.rto_couriername1 = rto_couriername1;
}
public String getEntity_id1() {
return entity_id1;
}
public void setEntity_id1(String entity_id1) {
this.entity_id1 = entity_id1;
}
public String getPostal_code1() {
return postal_code1;
}
public void setPostal_code1(String postal_code1) {
this.postal_code1 = postal_code1;
}
public String getCity1() {
return city1;
}
public void setCity1(String city1) {
this.city1 = city1;
}
public String getState1() {
return state1;
}
public void setState1(String state1) {
this.state1 = state1;
}
public String getCountry1() {
return country1;
}
public void setCountry1(String country1) {
this.country1 = country1;
}
public String getDays_to_deliver1() {
return days_to_deliver1;
}
public void setDays_to_deliver1(String days_to_deliver1) {
this.days_to_deliver1 = days_to_deliver1;
}
public String getCod1() {
return cod1;
}
public void setCod1(String cod1) {
this.cod1 = cod1;
}
public String getPg1() {
return pg1;
}
public void setPg1(String pg1) {
this.pg1 = pg1;
}
public String getRpu1() {
return rpu1;
}
public void setRpu1(String rpu1) {
this.rpu1 = rpu1;
}
public String getUpdated_by1() {
return updated_by1;
}
public void setUpdated_by1(String updated_by1) {
this.updated_by1 = updated_by1;
}
public String getUpdated_at1() {
return updated_at1;
}
public void setUpdated_at1(String updated_at1) {
this.updated_at1 = updated_at1;
}
public String getCod_couriername1() {
return cod_couriername1;
}
public void setCod_couriername1(String cod_couriername1) {
this.cod_couriername1 = cod_couriername1;
}
public String getPg_couriername1() {
return pg_couriername1;
}
public void setPg_couriername1(String pg_couriername1) {
this.pg_couriername1 = pg_couriername1;
}
public String getRto_couriername1() {
return rto_couriername1;
}
public void setRto_couriername1(String rto_couriername1) {
this.rto_couriername1 = rto_couriername1;
}
}
Here is My Database connection Class
package org.sanket.zivameDataBase.adminPostalCode.DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
public class DataBaseConnection {
public Connection getConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/zdb";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
return connection;
} catch (Exception e)
{
throw e;
}
}
}
Here is my access class.
package org.sanket.zivameDataBase.adminPostalCode.DataBase;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.sanket.zivameDataBase.adminPostalCode.model.AdminPostalCode;
public class Access {
public List<AdminPostalCode> getAdminPostalCode(int code,Connection con) throws SQLException
{
List<AdminPostalCode> adminDetail = new ArrayList<AdminPostalCode>();
PreparedStatement stmt = con.prepareStatement("select * from admin_postalcode where postal_code ="+code+"");
ResultSet resultSet = stmt.executeQuery();
//System.out.println(resultSet);
try
{
while (resultSet.next())
{
AdminPostalCode adminPostalCode = new AdminPostalCode();
adminPostalCode.setEntity_id1(resultSet.getString("entity_id"));
adminPostalCode.setPostal_code1(resultSet.getString("postal_code"));
adminPostalCode.setCity1(resultSet.getString("city"));
adminPostalCode.setState1(resultSet.getString("state"));
adminPostalCode.setCountry1(resultSet.getString("country"));
adminPostalCode.setDays_to_deliver1(resultSet.getString("days_to_deliver"));
adminPostalCode.setCod1(resultSet.getString("cod"));
adminPostalCode.setPg1(resultSet.getString("pg"));
adminPostalCode.setRpu1(resultSet.getString("rpu"));
adminPostalCode.setUpdated_by1(resultSet.getString("updated_by"));
adminPostalCode.setUpdated_at1(resultSet.getString("updated_at"));
adminPostalCode.setCod_couriername1(resultSet.getString("cod_couriername"));
adminPostalCode.setPg_couriername1(resultSet.getString("pg_couriername"));
adminPostalCode.setRto_couriername1(resultSet.getString("rto_couriername"));
adminDetail.add(adminPostalCode);
}
}catch (SQLException e)
{
e.printStackTrace();
}
return adminDetail ;
}
}
Now I want to write JUnit test case for Above code. And I tried in following way. But it is not working Please Help me in writing JUnit Test case. Remaining Everything is working fine.
package adminPostalCode;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.sanket.zivameDataBase.adminPostalCode.DataBase.Access;
import org.sanket.zivameDataBase.adminPostalCode.DataBase.DataBaseConnection;
import org.sanket.zivameDataBase.adminPostalCode.model.AdminPostalCode;
public class SampleTest {
List<AdminPostalCode> detailsActual = new ArrayList<AdminPostalCode>();
List<AdminPostalCode> detailsExpected = new ArrayList<AdminPostalCode>();
boolean abc;
AdminPostalCode adminPoCo = new AdminPostalCode();
public SampleTest()
{
adminPoCo.setCity1("WEST CHAMPARAN");
adminPoCo.setCod1("0");
adminPoCo.setCod_couriername1("NO SERVICE");
adminPoCo.setDays_to_deliver1("11");
adminPoCo.setEntity_id1("19625");
adminPoCo.setPg1("1");
adminPoCo.setPg_couriername1("INDIA POST");
adminPoCo.setPostal_code1("845106");
adminPoCo.setRpu1("0");
adminPoCo.setRto_couriername1("NO SERVICE");
adminPoCo.setState1("BIHAR");
adminPoCo.setUpdated_by1("panindra#milastar.in");
adminPoCo.setUpdated_at1("2015-03-19 19:30:22.0");
adminPoCo.setCountry1("IN");
detailsExpected.add(adminPoCo);
}
#Test
public void test() throws Exception {
//fail("Not yet implemented");
DataBaseConnection db = new DataBaseConnection();
Connection con = db.getConnection();
Access access = new Access();
detailsActual =access.getAdminPostalCode(845106, con);
abc = (detailsActual.equals(detailsExpected)) ;
System.out.println(abc);
}
}
use assertXxx in junit instead of System.out. junit is used to automate your test and find potential problems in your code and provide useful information about them. junit will help much less if you use System.out.
if you use junit to write a unit test, you should not connect the 'real' database, you should use some mock framework such as mockito to mock an Access object.
if you want write integration test using junit, you should use some specific junit extension framework like dbunit.
You have to use assertEquals for testing
assertEquals(detailsActual,detailsExpected);
if you are comparing arrayList object, you have to convert them to array than you can use assertArrayEquals.
It seems what you are looking for is away to compare 2 objects of type ArrayList.
The answer to this is by overriding equals method.
Add the below code to your AdminPostalCode POJO class.
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final AdminPostalCode other = (AdminPostalCode) obj;
if (city1 == null) {
if (other.city1 != null)
return false;
} else if (!city1.equals(other.city1))
return false;
if (cod1 == null) {
if (other.cod1 != null)
return false;
} else if (!cod1.equals(other.cod1))
return false;
if (cod_couriername1 == null) {
if (other.cod_couriername1 != null)
return false;
} else if (!cod_couriername1.equals(other.cod_couriername1))
return false;
if (country1 == null) {
if (other.country1 != null)
return false;
} else if (!country1.equals(other.country1))
return false;
if (days_to_deliver1 == null) {
if (other.days_to_deliver1 != null)
return false;
} else if (!days_to_deliver1.equals(other.days_to_deliver1))
return false;
if (entity_id1 == null) {
if (other.entity_id1 != null)
return false;
} else if (!entity_id1.equals(other.entity_id1))
return false;
if (pg1 == null) {
if (other.pg1 != null)
return false;
} else if (!pg1.equals(other.pg1))
return false;
if (pg_couriername1 == null) {
if (other.pg_couriername1 != null)
return false;
} else if (!pg_couriername1.equals(other.pg_couriername1))
return false;
if (postal_code1 == null) {
if (other.postal_code1 != null)
return false;
} else if (!postal_code1.equals(other.postal_code1))
return false;
if (rpu1 == null) {
if (other.rpu1 != null)
return false;
} else if (!rpu1.equals(other.rpu1))
return false;
if (rto_couriername1 == null) {
if (other.rto_couriername1 != null)
return false;
} else if (!rto_couriername1.equals(other.rto_couriername1))
return false;
if (state1 == null) {
if (other.state1 != null)
return false;
} else if (!state1.equals(other.state1))
return false;
if (updated_at1 == null) {
if (other.updated_at1 != null)
return false;
} else if (!updated_at1.equals(other.updated_at1))
return false;
if (updated_by1 == null) {
if (other.updated_by1 != null)
return false;
} else if (!updated_by1.equals(other.updated_by1))
return false;
return true;
}
The above method will help you compare the 2 Actual and Expected objects.
Though, a correct JUnit will make use of assertEquals, verify, etc to validate results
Your AdminPostalCode class should implement boolean equals(Object other) and also int hashCode(). Implementing these methods will guarantee that custom objects, like your AdminPostalCode class, will be able to perform checks on certain fields. assertEquals(detailsActual, detailsExpected) f.e. invokes this method internally. By default equals(...) compares objects on their memory address instead of the content. That's why you should overwrite these two methods.
If you don't want to overwrite these methods (for whatever reason), you also have the possibility to implement custom Hamcrest matchers which will perform the equality check. You are then able to utilize this matcher like this: assertThat(detailsActual, containsAdminPostalCodes(detailsExpected)); where containsAdminPostalCodes(...) is your custom Hamcrest matcher which takes a List of AdminPostalCode as input. Inside this Hamcrest matcher you will need to compare the fields of the AdminPostalCode instances of the actual list with the one provided in the expected list.
Hamcrest comes already with quite a lot of matchers. So check if there are already any available that suits your need, though some may rely on a correct implementation of equals(...) and hashCode().
Also, as #walsh has correctly pointed out, you should not call a database in your unit-test directly but instead use mocked objects (Mockito, PowerMock, ...). If you write integration tests (our company f.e. prefers integration tests over unit-tests), try to refactor the initialization and tear-down code for your database into JUnit rules

Testing controllers using Spring, JUNIT, MockMvc and Hamcrest

I am trying to test a controller of mine which returns me a List of Objects on the get method to populate a dropdown on my page.
I am trying to write a JUnit test using MockMvc and Hamcrest to test the same.
I want to compare the List of objects and test if it fails or not.
I have created a static List of objects in my Test.java and I am getting a List of objects from the model.attribute method.
To Test: if both the List of Objects are equal and don't contain any other objects.
My object is called Option which has 3 properties. Key, Value and Selected. I have to check if the all the keys exists in the List or not.
I am unable to create a matcher to do the same. I am trying to create a matcher to compare my List.
So far I have done the following:
#Before
public void setup() throws Exception {
// This would build a MockMvc with only the following controller
this.mockMvc = MockMvcBuilders.standaloneSetup(openAccountController)
.build();
}
#Test
public void testOpenAccount() {
try {
setAllLegislations();
this.mockMvc
.perform(get("/open_account.htm"))
// This method is used to print out the actual httprequest
// and httpresponse on the console.
.andDo(print())
// Checking if status is 200
.andExpect(status().isOk())
.andExpect(
model().attributeExists("appFormAccountPlans",
"appFormLiraLegislations",
"appFormLrspLegislations",
"appFormRlspLegislations"))
.andExpect(
model().attribute("appFormAccountPlans", hasSize(5)))
.andExpect(
model().attribute("appFormLiraLegislations",
hasSize(8)))
.andExpect(
model().attribute("appFormLrspLegislations",
hasSize(2)))
.andExpect(
model().attribute("appFormRlspLegislations",
hasSize(1)))
.andExpect(
model().attribute(
"appFormLiraLegislations",
hasKeyFeatureMatcher(getLiraLegislations(allLegislations))));
private Matcher<List<Option>> hasKeyFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "was") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (actualOptions.size() == expectedOptions.size()) {
for (Option expectedOption : expectedOptions) {
for (Option actualOption : actualOptions) {
if (expectedOption.getKey().equals(
actualOption.getKey())) {
flag = true;
} else {
flag = false;
break;
}
}
}
}
if (flag)
return actualOptions;
else
return null;
}
};
}
private List<Option> getLiraLegislations(List<Option> legislation) {
List<Option> liraLegislations = new ArrayList<Option>();
Iterator<Option> iterator = legislation.iterator();
while (iterator.hasNext()) {
Option option = iterator.next();
if (LIRA_LEGISLATIONS.contains(option.getKey())) {
liraLegislations.add(option);
}
}
return liraLegislations;
}
private List<Option> allLegislations;
public List<Option> getAllLegislations() {
return allLegislations;
}
public void setAllLegislations() {
allLegislations = new ArrayList<Option>();
for (String key : ALL_LEGISLATIONS) {
Option option = new Option();
option.setKey(key);
allLegislations.add(option);
}
}
private static final Set<String> ALL_LEGISLATIONS = new HashSet<String>(
Arrays.asList(AccountLegislationEnum.AB.toString(),
AccountLegislationEnum.MB.toString(),
AccountLegislationEnum.NB.toString(),
AccountLegislationEnum.NL.toString(),
AccountLegislationEnum.NS.toString(),
AccountLegislationEnum.ON.toString(),
AccountLegislationEnum.QC.toString(),
AccountLegislationEnum.SK.toString(),
AccountLegislationEnum.BC.toString(),
AccountLegislationEnum.FE.toString(),
AccountLegislationEnum.NT.toString(),
AccountLegislationEnum.PE.toString(),
AccountLegislationEnum.YT.toString(),
AccountLegislationEnum.NU.toString(),
AccountLegislationEnum.UNKNOWN.toString()));
This is how I am getting my model attribute as:
Attribute = appFormLiraLegislations
value = [com.abc.arch.core.gui.eform.gui.Option#199d1739, com.abc.arch.core.gui.eform.gui.Option#185fac52, com.abc.arch.core.gui.eform.gui.Option#312a47fe, com.abc.arch.core.gui.eform.gui.Option#4edc8de9, com.abc.arch.core.gui.eform.gui.Option#71e8e471, com.abc.arch.core.gui.eform.gui.Option#70edf123, com.abc.arch.core.gui.eform.gui.Option#15726ac1, com.abc.arch.core.gui.eform.gui.Option#abeafe7]
Thanks in advance.
You can make your life definitely easier when you correctly implement Option object hashCode() and equals() methods using key attribute; then you can simply write:
model().attribute("appFormLiraLegislations",getLiraLegislations(allLegislations)))
and rely on list1.equals(list2) method to do the work for you.
Option hashCode and equals implementation:
public class Option {
private String key;
private String label;
...
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Option other = (Option) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
Methods above are generated by my IDE. I also don't know exactly what is structure of your Option class, so I add label property for example in addition to key property.
I created a custom Hamcrest matcher to compare the List of Option by checking the size and the keys.
private Matcher<List<Option>> hasOptionsFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "Options were") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (expectedOptions.size() == actualOptions.size()) {
for (Option expected : expectedOptions) {
for (Option actual : actualOptions) {
if (expected.getKey().equals(actual.getKey())) {
flag = true;
break;
} else {
flag = false;
}
}
}
} else
flag = false;
if (flag)
return expectedOptions;
else
return null;
}
};
Implementation would be as follows:
private static final ImmutableBiMap<String, String> LIRA = new ImmutableBiMap.Builder<String, String>()
.put(AccountLegislationEnum.AB.toString(), "ALBERTA")
.put(AccountLegislationEnum.MB.toString(), "MANITTOBA")
.put(AccountLegislationEnum.NB.toString(), "NEW BRUNSWICK")
.put(AccountLegislationEnum.NL.toString(), "NEWFOUNDLAND")
.put(AccountLegislationEnum.NS.toString(), "NOVA SCOTIA")
.put(AccountLegislationEnum.ON.toString(), "ONTARIO")
.put(AccountLegislationEnum.QC.toString(), "QUEBEC")
.put(AccountLegislationEnum.SK.toString(), "SASKATCHEWAN")
.put(AccountLegislationEnum.UNKNOWN.toString(), "UNKNOWN").build();
private List<Option> prepareOptions(ImmutableBiMap<String, String> map) {
List<Option> legislations = new ArrayList<Option>();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Option option = new Option();
option.setKey(key);
option.setValue(value);
legislations.add(option);
}
return legislations;
}
.andExpect(model().attribute("appFormLiraLegislations",hasOptionsFeatureMatcher(prepareOptions(LIRA))))

How do I use contains to search through a custom object ArrayList for a particular string?

I'm completely brand new to programming (started yesterday...) and Java so excuse any stupid mistakes and really awful code (I have no clue how to order/format). I've been given a task to make an inventory of videos and I want to be able to search through the inventory to check if a particular video is there.
I know I can use contains to do this but I can't get it to work with my custom objects ArrayList (videos) and I want it to search through all the data (each InventoryRow below). I've overridden equals and HashCode but it still won't work - whenever I try to run the code it will always tell me it can't find the video even if the video is there. (FYI I use contains towards the end of my code under the rent and check functions)
I'd really appreciate any help as I've been googling all day to no avail. Also if this can't be done or another method would be better please let me know! Thanks.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
class InventoryRow {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((availability == null) ? 0 : availability.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((returndate == null) ? 0 : returndate.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InventoryRow other = (InventoryRow) obj;
if (availability == null) {
if (other.availability != null)
return false;
} else if (!availability.equals(other.availability))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (returndate == null) {
if (other.returndate != null)
return false;
} else if (!returndate.equals(other.returndate))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
private String name;
private String type;
private Character availability;
private String returndate;
public InventoryRow(String name, String type, Character availability,
String returndate) {
this.name = name;
this.type = type;
this.availability = availability;
this.returndate = returndate;
}
public String getReturndate() {
return returndate;
}
public void setReturndate(String returndate) {
this.returndate = returndate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Character getAvailability() {
return availability;
}
public void setAvailability(Character availability) {
this.availability = availability;
}
public String toString() {
return name + " " + type + " " + availability + " " + returndate;
}
}
public class InventorySort {
public static void main(String[] args) {
List<InventoryRow> videos = new ArrayList<InventoryRow>();
videos.add(new InventoryRow("Casablanca", "Old", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
"1 January 2015"));
videos.add(new InventoryRow("2012", "Regular", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Ant-Man", "New", 'Y', "1 January 2015"));
// Another ArrayList because I can't seem to search through the first
// one?
/*ArrayList<String> names = new ArrayList<String>();
names.add("Casablanca");
names.add("Jurassic Park");
names.add("2012");
names.add("Ant-Man");*/
Scanner input = new Scanner(System.in);
// Output the prompt
System.out.println("What do you want to do?");
// Wait for the user to enter a line of text
String line = input.nextLine();
// List, rent and check functions
// List function
if (line.equals("l")) {
// Sort function
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
// Rent function
} else if (line.equals("r")) {
System.out.println("Which video would you like to rent?");
String line2 = input.nextLine();
// Search through ArrayList
if (videos.contains(line2)) {
System.out.println("Video available to rent!");
} else {
System.out.println("Video unavailable to rent.");
}
// Check function
} else if (line.equals("c")) {
System.out
.println("Which video would you like to check is in the inventory?");
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(line3)) {
System.out.println("Video found!");
} else {
System.out
.println("Video not found. Please see the inventory below.");
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
// If anything else is entered
} else {
System.out
.println("The only options are to list (l), rent (r) or check (c).");
}
}
}
You can use contains. But, for the first day of programming, it might be more understandable to simply iterate over your inventory, comparing the input string with the video name:
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line3.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");
Alternative to #kilo answer, you could implement equals and hashcode method only on the name of video class and check it in the following way.
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(new Video(line3, null, null, null))) {
System.out.println("Video found!");
}
This will return contains = true only if the name matches.

New user held with searching array

I am trying to search an array and if the two Strings are matched then it will return true otherwise false, firstly i want to search to see if the account is already there if so then search Code if the two exsis then return true
public boolean searchArray(String account, String code) {
for (Accounts a : bAccounts) {
if (a.getAccount().equals(account)) {
for (Accounts c : bAccounts) {
if (c.getCode().equals(Code))
return true;
}
}
}
return false;
}
Think I've got a little lost within this search method, can anyone please help me on this, thanks. This all compiles fine but doesn't seem to return anything. I have get methods in my Accounts class which has get and set methods for Account and Sort.
public boolean searchArray(String account, String code) {
for (Accounts a : bAccounts) {
if (a.getAccount().equals(account)
&& a.getCode().equals(code)) {
return true;
}
}
return false;
}
Inner for should be removed.
You didn't mention if you'll accept nulls for account and code parameters.
If null values are possible/desirable to compare, this is what I suggest:
public boolean searchArray(String account, String code) {
for (Account a : accounts) {
if (account == null) {
if (code == null) {
if ((a.getAccount() == null) && (a.getCode() == null)) {
return true;
}
} else {
if ((a.getAccount() == null) && code.equals(a.getCode())) {
return true;
}
}
} else {
if (code == null) {
if (account.equals(a.getAccount()) && (a.getCode() == null)) {
return true;
}
} else {
if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
return true;
}
}
}
}
return false;
}
If you won't consider nulls for account and code parameters, I suggest this:
public boolean searchArray(String account, String code) {
// if you won't consider nulls then there's no need to search
// when at least one of them is null
if ((account == null) || (code == null)) {
return false;
}
for (Account a : accounts) {
if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
return true;
}
}
return false;
}
Hope it helps you

Categories