I tried to make a method to tell me if my array contained any duplicate coordinates, and if so set a boolean to true, else, set it to false. Any idea why it continuously returns false?
public void check(){
if(point[particle].equals(point) == true){
check = true;
} else {
check = false;
}
}
point = Point array
particle = Current particle
check = My boolean used to check
Look at this part of the code (from the condition of your if-statement):
point[particle].equals(point)
I think there is some variable shadowing (or something of that sort) going on here. point seems to be an array but you are testing for equality between a member of this array and the array itself -- this is why you keep getting false. Check your variable names and see if you accidentally used the same name for two different variables.
As a note,
if (condition == true) {
check = true;
} else {
check = false;
}
can be simplified to
check = condition;
Related
I was writing a list of menu for my product and wanted to use a simple String (and wanted to use .equalsIgnoreCase() so that it would ignore whatever text casing it is) and compare it in ArrayList pre-coded (as i was adding a new product) using .contain(); however it still depends on text casing and I couldn't find answers. Hoping that someone would help me :).
static void AddProductCode() {
boolean print = true;
for (int i = 0; i < product.size(); i++) {
System.out.println(productcode.get(i)+" " +product.get(i)+" "+ productprice.get(i));
}
System.out.print("PRODUCT CODE : ");
code = scan.next();
code.equalsIgnoreCase(code);
boolean check = productcode.contains(code);
if(check == true){
System.out.println("CODE IS UNAVAILABLE");
AddProductCode();
}
else {
AddProduct2nd();
}
}
The List#contains(Object) compares the given object with each element of the list using the equals() method. The String#equals() method checks equality by taking the case into consideration.
So, for that you can manually implement the logic.
Replace the boolean check = productcode.contains(code); with
boolean check = false;
for (String e: productcode) {
if (e.equalsIgnoreCase(code)) {
check = true;
break;
}
}
Now, check will be true if code is present in productcode irrespective of the case. If check is false this means that code is not present in productcode
I've been developing a small application for work, and I've come across something I can't figure out.
In the following code, I have an ArrayList of a Custom Class called 'Product' that contains data of type 'String'. I use the .contains method on this ArrayList to ensure it doesn't contain a certain String.
My IDE gives me the warning of 'Suspicious call to java.util.Collections.contains: Given object cannot contain instances of String (expected Product)'.
I completely understand the above message, because I'm comparing two different Types, so how can it ever evaluate correctly? I'm thinking it must be because the 'Product' class contains the data I want to compare, it is defaulting to using the toString method on the Product class (I override this in the Class) and comparing it with the String I want to compare it against.
It seems like JVM black magic to me.
private void createOrderListing(List<String[]> orderList)
{
//For each line of the order list file
for(String[] s : orderList)
{
if(s.length >= 28) //OrderLine should be of this length
{
if (!s[0].equalsIgnoreCase("ProductCode") && !s[0].isEmpty()) //Makes sure we're not including headers
{
//How does this bit work?
if(!productListing.contains(s[0]))
{
OrderLine order = new OrderLine();
//References product code of Product against Order Line, if match, then pack sizes and other basic fields ammended as appropriate
boolean productFound = false;
for (Product p : productListing)
{
if (s[0].contentEquals(p.getProductCode()))
{
order.initialAmendOrderLine(p.getProductCode(), p.getProductName(), p.getPackSize(), p.getProductType());
productFound = true;
}
}
if(productFound)
{
order.setOrderValues(s);
orderListing.add(order);
}
}
//System.out.println("\nOrder Product is: " + order.getProductName()+ "\nOrder Pack Size is: " + order.getInternalPackSize());
}
}
}
}
UPDATE
The reason this works as pointed out in the comments is that the block is always true (the .contains method is always false, the ! inverses this, hence true). Sorry for the confusion and pointing out my carelessness.
Here is an implementation of contains method in ArrayList that I have in OpenJDK:
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
Basically, there is nothing complex in it. It iterates through the all elements of your ArrayList and checks whether your given object is equal to the current one. If the condition is true then element exists in the list.
So let's imagine that you are passing String "SomeValue" to this method. Elements of ArrayList are iterated and following action is executed: "SomeValue".equals(elementData[i]) where elementData[i] is a product.
Since equals method of String class cannot compare String with a Product it returns false and as a result, you get false from contains method.
To fix this situation you can iterate over ArrayList manually and compare some Product's field with your string. E.g. you can implement following contains method:
public boolean contains(List<Product> products, String yourStringValue) {
for (Product p : products) {
if(p.getProductCode().equals(yourStringValue)){
return true;
}
}
return false;
}
productListing is a list of Product objects. Yet you are asking the list if it contains a specific String object -- which shouldn't ever happen.
What you should do is check if your Product#getProductCode is equal to your specific String. This can be acheived by using streams:
if(!productListing.contains(s[0])) // replace this
// with this
if (!productListing.stream().filter(o -> o.getProductCode().equals(s[0])).findFirst().isPresent())
What does this code do? It checks all your Product elements to find one whose myStringData attribute is equal to the String you're comparing.
since contains relays on equals implementation, when you do
if(!productListing.contains(s[0]))
you are asking the list OF ARRAYS OF STRINGS if its contains a String.
that will return always false because the type are different, so is not that is working at all, is that your condition will always return false
I'm trying to make a bit of code that returns a boolean value depending on whether an item was successfully removed from a HashMap or not.
My understanding is that map.remove(Key) should return the Key if it worked and null if not. My approach was to check if the return value is null and print false if it is, true if anything else.
The problem I'm having comes from that I don't know how to check what the return value was inside my method.
Here is my attempt so far.
public boolean deleteMapEntry(String entry)
{
testMap.remove(entry);
if(null)
{
return false;
}
else
{
return true;
}
}
Obviously saying if (null) doesn't work, but I can't find what would.
You need to assign the value of testMap.remove(entry) to a variable to test it to see if it is null...
String value = testMap.remove(entry);
return value != null;
you can also just test what you remove directly and not use a variable:
return testMap.remove(entry) != null;
I'm working on a basic Java assignment for school. This snippet involves searching for a specific part number in an ArrayList. When I try to compile, the IDE says I have a missing return statement. However, I can't see where it is. Do I need a return statement following the increment of the index? If so, then the return null becomes unreachable. Thank you guys very much.
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
boolean searching = true;
while (index < items.size() && searching){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == (searchPartNumber)){
searching = false;
return inventoryItem;
}
else{
index++;
}
if(searching){
return null;
}
}
}
your code has several problems:
after you compared first item in list and it does not match - you will stop comparing, as searching is true and you will return null
in case of empty list you need to return null too
here is the fixed version:
public InventoryItem findInventoryItem(int searchPartNumber) {
for (InventoryItem inventoryItem : items)
if (inventoryItem.getPartNumber() == searchPartNumber)
return inventoryItem;
return null;
}
The method expected a return value in all cases. This means you have to add a return value in the else-block, too. Or you could add a return value only once at the end of all statements.
you're not handling the case where search will not be true.
That is,
if(searching){
return null;
}
Where is the else part handled here?
No matter what happens in your method, there has to be some value returned (even if it is null).
Right now, if you never get into your while (because that condition isn't fulfilled to begin with -> like when items.size() is 0), your method won't return anything.
In other words: Put a return null; after the closing bracket of your while loop.
Another important note: You do realize that this while will always only look at the first item, right? Because if your first item is not the one you're searching for, your variable searching will still be true, which will then force the method to return null (without looking at any other items)
You are missing a return statement right at the end, after the while loop.
This is needed to handle the case where the while loop guard becomes false, either by items being empty, or searching being set to false.
The compiler has no way of determining whether these will never become false, so you it requires you to return in case they do.
All functions that have a type (aren't void) require that you return something based on the method signature. This means that you must return something in ALL cases. You haven't included the case where searching is not true, and must return something if that is the case.
if(searching){
return null;
} else{
//return something else
}
It is important to note though that in this case the else is implicit, and therefore you don't actually have to provide the else. You could instead just do this:
if(searching){
return null;
}
//return something else
Keep in mind that if searching is true, it will return null and "return something else" will never be called.
Do like this
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
//boolean searching = true; comment out this line
InventoryItem inventoryItem = null; //declare null InventoryItem here
while (index < items.size())
{
inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if (fetchedPartNumber == (searchPartNumber))
{
//searching = false; comment out this line
break; //do something to get out from while loop
}
else {
inventoryItem = null;
index++;
}
}
return inventoryItem; //if found then it will have item otherwise null
}
First you need to return if items.size equals zero. Second you need to return if you find nothing. Third I can't see any usefulness of the variable searching.
You could change your searching function a bit. The final form would be something like this:
public InventoryItem findInventoryItem(int searchPartNumber) {
int index = 0;
while (index < items.size()){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == searchPartNumber)
return inventoryItem;
else
index++;
}
return null;
}
I am working on an ATM simulation program. Currently I'm working on methods to verify the user input. I have an arraylist with bank card objects these objects consist of 3 variables I want
to check if a given reknr and pasnr combination is equal with any reknr and pasnr combination in my arraylist with the bankcard objects. If the arraylist contains the given combination the method has to return true, otherwise it has to return false.
public static boolean reknrpasnrCheckOke(String reknr,String pasnr){
for (int i=0; i<rekpaspin.size(); i++){
if (rekpaspin.get(i).reknr.equals(reknr) && rekpaspin.get(i).pasnr.equals(pasnr))
return true;
}
return false;
}
}
It doesn't matter what the input is it always returns false, how to solve this?
Edit::
I forgot an { after the if so I changed the code to:
public static boolean reknrpasnrCheckOke(String reknr,String pasnr){
for (int i=0; i<rekpaspin.size(); i++){
if (rekpaspin.get(i).reknr.equals(reknr) && rekpaspin.get(i).pasnr.equals(pasnr)){
return true;
}
}
return false;
}
But still the same problem.
You are only checking the first item in the list. If it's not matching, then you immediately return false without checking the rest of the items.
Move the return false; after the end of the for loop.
To evaluate equality of objects by means other that memory reference, you have to override the equals() method and hashcode() method of you rekpaspin class.
Also, you should not use an ArrayList<> and search it each time. Consider using a Set or HashMap
First, as stated by #rgettman, if the first 'if' check doesn't match, you automatically return false, so it needs to arranged better.
However, in this case you probably want to use a boolean flag. It should be set to false until the case matches, in which case you would set the flag to true. Outside the loop you would return the flag.