Java ( Reading userinput.equalsIgnoreCase() in Arraylist) - java

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

Related

Why does .contains method on ArrayList of custom instances work?

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

How to NOT find something in JAVA?

EDIT :
ok, sorry for not so clear question. Let's try other way:
We have an ArayList of names : Peter, John, Adam
We are looking for String name;
If ArrayList contains the String, we want to write the String. If ArrayList doesn't contains the String, we want to add the String into the ArrayList.
If I'm looking for "Adam", then this program is not working, because first it finds name "Peter", then "John", and only after that it finds "Adam". So for the first 2 times, it thinks, "Adam" is not in the list, and acts so.
String findName;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().contains(findName)) {
System.out.println(findName);
break;
}
else
arrayList.add(findString);
}
Original question :
I have a String and an Array (ArrayList). I have to do something, if the String is in the Array and something else, if it is not in the Array. How do I do that?
I can't do it like this :
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
break;
}
else
DO SOMETHING ELSE;
}
because it will find the String only once and all the other times it will act, like the arraylist doesn't contains the String.
So I'm doing it like this :
String findString = "0";
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
findString = "2"; //when I find the String, I change this
break;
}
if findString == "0"; //if I have not found the String, this happens
DO SOMETHING ELSE;
}
and I have the feeling, it should be not done like this. ;)
I know I can use booleans instead of this way, but it's the same in other way. Isn't there total different way of doing this correctly?
Cleanest way is as follows: Declare a method which returns whether the string is in the array:
public boolean arrContainsStr(String str, String[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(str)) {
return true;
}
}
return false;
}
Then use this method in your code like this:
String myString;
String[] myArray;
if (arrContainsStr(myString, myArray)) {
DO SOMETHING;
}else {
DO SOMETHING ELSE;
}
This is for primitive string arrays. Note that if you are using an ArrayList or similar, you can simply use the .contains(myString) method to check if the list contains your string. Documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
This question is a bit odd, but just reading your first sentence, if you want to see if a List e.g. ArrayList contains an object (e.g. a String) you can just use the contains(Object o) method rather than looping through. I must be missing your point. In any case, an example:
String stringToFind = "Foo";
List<String> stringList = new ArrayList<>();
stringList.add("Foo");
if (stringList.contains(stringToFind)) {
System.out.println("String found");
} else {
System.out.println("String not found");
}
Output: String found. (In this example).
Couldn't you use .contains as below to check if the String is in the list?
if(arrayList.contains(myString)){
// DO SOMETHING
} else {
// DO SOMETHING ELSE
}
You could set a boolean to true if you find your value then break.
If you don't find the value, the boolean will stay to false.
Then you do the if
Its a little vague so I'm not sure if this is what you want, but if you remove the break in the first segment of code i think you will get what you want. do you want it do DO SOMETHING for every occurrence of the string or just the first one. also if you do need the break you could check the value of i after the loop terminates so
if(i==arrayList.size())
{
//String found
}
else
{
//String not found
}

What is the correct syntax of a method that deletes part of a list and returns true if succesful?

I m trying to create a method that searches the content of a list called authors looking for the element (the author's name) given as arg, and then deletes the specific field. If successful it returns true. But it won't work for some reason. I believe the error lies in the authors.remove(authorName); because the main class will not erase anything when given the order Book.removeAuthorByName("White");.
public boolean removeAuthorByName(String authorName){
boolean val = authors.contains(authorName);
for (int i = 0; i <= numAuthors; i++){
if(val = true){
authors.remove(authorName);
authors.trimToSize();
}
}
return val;
}
public int listSize(){
return authors.size();
}
Little more concise and better will be
public boolean removeAuthorByName(String authorName){
int index = authors.indexOf(authorName);
if(index > -1){
authors.remove(index);
return true;
}
return false;
}
First of all, you should check whether your list supports the remove(Object) method; it does because otherwise you would have received an UnsupportedOperationException.
You can simply have to call authors.remove(name); the method will return true if the passed name was found and deleted successfully - see the documentation.
Remove the while loop check using if clause. Also check case sensitivity
if(list.contains(authorname)){
list.remove(authorname);
return true;
}
else
{
return false;
}

Print Tree components

I am new to java and I want to create a very simple "word completion " program. I will be reading in a dictionary file and recursively adding the words into a Node array (size 26). I believe I have managed to do this successfully but I am not sure how to go through and print the matches. For the sake of testing, I am simply inserting 2 words at the moment by calling the function. Once everything is working, I will add the method to read the file in and remove junk from the word.
For example: If the words "test" and "tester" are inside the tree and the user enters "tes", it should display "test" and "tester".
If somebody could please tell me how to go through and print the matches (if any), I would really appreciate it. Full code is below.
Thank you
What you implemented is called "trie". You might want to look at the existing implementations.
What you used to store child nodes is called a hash table and you might want to use a standard implementations and avoid implementing it yourself unless you have very-very specific reasons to do that. Your implementation has some limitations (character range, for example).
I think, your code has a bug in method has:
...
else if (letter[val].flag==true || word.length()==1) {
return true;
}
If that method is intended to return true if there are strings starting with word then it shouldn't check flag. If it must return true if there is an exact match only, it shouldn't check word.length().
And, finally, addressing your question: not the optimal, but the simplest solution would be to make a method, which takes a string and returns a node matching that string and a method that composes all the words from a node. Something like this (not tested):
class Tree {
...
public List<String> matches(CharSequence prefix) {
List<String> result = new ArrayList<>();
if(r != null) {
Node n = r._match(prefix, 0);
if(n != null) {
StringBuilder p = new StringBuilder();
p.append(prefix);
n._addWords(p, result);
}
}
return result;
}
}
class Node {
...
protected Node _match(CharSequence prefix, int index) {
assert index <= prefix.length();
if(index == prefix.length()) {
return this;
}
int val = prefix.charAt(index) - 'a';
assert val >= 0 && val < letter.length;
if (letter[val] != null) {
return letter[val].match(prefix, index+1);
}
return null;
}
protected void _addWords(StringBuilder prefix, List<String> result) {
if(this.flag) {
result.add(prefix.toString());
}
for(int i = 0; i<letter.length; i++) {
if(letter[i] != null) {
prefix.append((char)(i + 'a'));
letter[i]._addWords(prefix, result);
prefix.delete(prefix.length() - 1, prefix.length());
}
}
}
}
Maybe a longshot here, but why don't you try regexes here? As far as i understand you want to match words to a list of words:
List<String> getMatches(List<String> list, String regex) {
Pattern p = Pattern.compile(regex);
ArrayList<String> matches = new ArrayList<String>();
for (String s:list) {
if (p.matcher(s).matches()) {
matches.add(s);
}
}
return matches
}

Method should check array against itself?

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;

Categories

Resources