What does boolean do under these circumstances? - java

public static boolean containsAll(String[] strings, String test)
{
if (test == null || strings.length == 0) {
return false;
}
for (String str : strings)
if (!test.contains(str))
return false;
return true;
}
I have no idea what I can add to a boolean inside the parentheses but I have this line of function in my script with help from a fellow SOF member.
Thing is, how do I know what to write in a parenthesis to declare stuff? I don't know the rules from my memory and I don't have any source I can relate to. Basically I have no idea why there is an array and a string declared in the parentheses.
Basically,
1) Why is there a line declaring an array and a string inside the parentheses?
2) Where can I relate to as a source to get more information about classes like "boolean" and what I can do to change their functions? Basically I want a book-like website I can relate to whenever I don't know about something in java.

Why is there a line declaring an array and a string inside the parentheses?
So that you can use those parameters within the method , to achieve something .
From the method declaration it seems :
public static boolean containsAll(String[] strings, String test)
The method tries to search for a String passed as parameter test within an array passed as parameter strings and returns boolean true or false depending on whether the strings array contains the test String or not. Or probably , the method was named containsAll() to signify that it ascertain whether all the elements of strings array contains test string !
EDITED: The method checks if all the elements of the strings array contains the test String.
Where can I relate to as a source to get more information about classes like "boolean" and what I can do to change their functions
boolean is primitive , Boolean is a wrapper class. Your method returns boolean primitive.

Related

Check if String is in Arraylist

How can I check if my Input String is in my ArrayList?
I did it like this. But it always shows "not equal". Althoug I insert 1 for example:
public class Main {
public static void main(String[] args) {
String Input = JOptionPane.showInputDialog("Input:");
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
if (Input.equals(list)) {
JOptionPane.showMessageDialog(null, "equals");
} else {
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
If you want to check does List<T> contains T item you should use yourList.contains(T item) in your code, you are using item.equals(object) which is completely different. In short what equals() does is it checks do both objects are stored in the same memory address. Although for some default classes this method is overwritten and works a different way, String class is a good example of that.
Explanation
You wrote
if (Input.equals(list)) { ... }
with Input being a String and list an ArrayList. But, the String#equals (documentation) method compares if two Strings have the same characters (like "hello".equals("hello")), not if the argument list contains the element you called the method on. To quote from its documentation:
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Solution
What you actually want to use is List#contains (documentation):
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).
So the code might look like:
if (list.contains(Input)) { ... }
Naming convention
Please note naming conventions. Variable names should always be in camelCase, so input instead of Input. Same for method names.
Only class names are written in PascalCase. And constants (static final) are written in uppercase SNAKE_CASE.

error: method contains in class String cannot be applied to given types

this statement shows this error: method contains in class String cannot be applied to given types;
boolean m=str[j].contains(a);
why this happens and what is the remedy.It would be great if someone helps.. thank you..
Since the method contains() need to receive a CharSequence, probably your variable a is not an instance of CharSequence.
So, do a validation:
if(a instanceof CharSequence ){
boolean m=str[0].contains(a);
}
---- Edit
Try this:
CharSequence a = 'a'.toString();
boolean m = str[0].contains(a);
When you say str[j], you are subscripting it, so str[j] is a char. And contains() method cannot be applied on char. What you want to do is probably this :
String str = "StackOverflow";
boolean isOPresent = str.contains('O');
System.out.println(isOPresent); // will print true
Without the code that surrounds this statement it will be difficult to tell exactly what's wrong. But from that one line, my guess is that either the variable a is not of type char or str is not a string but rather a char as well. Post more code and maybe we can help more thoroughly
UPDATE:
The variable that is sent in to the 'contains' function must be of type CharSequence according to the Java Docs.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
http://docs.oracle.com/javase/7/docs/api/java/lang/CharSequence.html

Determine Subclass Type of an Object of the Parent Class

I have this problem where there are several parts in my code where I check if these certain conditions are met so that I can understand if what I am checking is of one type or the other. this ends up becoming large if else trees because I am making lots of checks, the same checks in each method, and there are several different types the thing I am checking can be. This I know can be solved using objects!
Specifically, the things I am checking are 4 string values from a file. based on these string values, the 4 strings together can make one of 3 types. Rather than making these same checks every time I need to get the type the 4 strings make up, I am wondering if I can create a general object given these 4 strings and then determine if that object is an instanceof either specific class 1, 2, or 3. Then I would be able to cast that general object to the specific object.
Say I name the general object that the 4 strings create called Sign. I would take those 4 strings and create a new Sign object:
Sign unkownType = new Sign(string1, string2, string3, string4);
I need to check which specific type of sign this sign is.
EDIT:
for more detail, the Signs I am checking are not symbols like "+" or "-", they are signs with text like you would see on the road. there are 4 lines on each sign and they need to be checked to see if each line evaluates to match a specific type of sign.
The first line of SignType1 will be different of the first line of SignType2, and I want to take those 4 lines (Strings) and pass it onto an object and use that object throughout my code to get the values from it rather than making the same checks in each method.
If you want me to show some code, I can, but it won't make much sense.
What you seem to asking for is a factory pattern
public interface ISign {
public void operation1();
public void operation2();
}
and a Factory class to generate classes based on input
public class SignGenerator {
public static ISign getSignObject(String str1,String str2, String str3, String str4) {
if(str1.equals("blah blah"))
return new FirstType();
if(str1.equals("blah blah2") && str2.equals("lorem ipsum"))
return new SecondType();
return new ThirdType();
}
}
public class FirstType implements ISign {
}
public class SecondType implements ISign {
}
public class ThirdType implements ISign {
}
Implement all Type specific logic in these classes so you can call them without checking with tons of if..else clauses first
From what I gathered from your statement.
Say: create the method that returns a certain object provided the given string is equal to whateva value you specify
//provided the objects to be returned are subtypes of Sign
public Sign getInstance(String first, String second, String third, String fourth)
{
if(first==null || second==null || third==null || fourth===null )
return null;
if(compare1.equals(first))
return new SignType1();
else
if(compare2.equals(second))
return new SignType2();
else
if(compare3.equals(third))
return new SignType3();
else
if(compare4.equals(fourth))
return new SignType4();
}
Above code checks and returns thee appropriet instance corresponding to the string passed
Hope that's what was your concern

Search method always null

I'm having issues with a method I've written to search a class called Item. No matter what I search, it is returning null. I believe I'm having issues with variable scope:
public Item search(String itemSearch) {
Item search = null;
for(Item i : items){
if (i.getName() == itemSearch){
search = i;
}
}
return search;
}
The getName method returns the name attribute of the item. No matter what the Item search is always null, I'm guessing this is due to variable scope and it is not assigning in the for each loop? Why is this method always null?
Thank you
You can't use the == to compare the content of two strings in java. You need to use the .equals() method
Using the == will only compare the adress of the two strings, while equals will compare their values.
You are comparing strings using ==. You should instead use equals() method. E.G
i.getName().equals(itemSearch)
Also instead of looping the entire loop use return i in the if statement, instead of assigning i to search and then returning search.

Creating compareTo method in java with one parameter

I have a question about making a compareTo function in Java.
In Java, we have the String.compareTo(String) method.
However, I need to make a compareTo function with only only parameter, like: compareTo(String).
I assume that I need to use this to hold another string.
For example:
public static boolean compareTo(String word)
{
private string this.word = word;
if(word.equals(this.word))
{
return true;
}
else
{
return false;
}
}
Is this the right idea?
Do I need to create get and set functions to hold first word to compare with second word?
Thanks
To compare two objects, you need to implement the Comparable interface. As part of the implementation, you will write your own compareTo() method. This method compares your current object with the object being passed.
public MyObj implements Comparable<MyObj> {
...
public int compareTo(MyObj anObj) {
// if your obj greater than anObj, return 1
// if equal, return 0
// else return -1
}
}
Further down in your code, you can then do --
`MyObj anObj = new MyObj();
MyObj anObj1 = new MyObj();
// anObj.compareTo(anObj1) ....
// This will also be useful if you have a collection of MyObjs.
Collections.sort(arrayListOfMyObjs);
That's not the right idea in many ways...
You cannot use this in a static function.
You cannot add a visibility declaration to a local variable of a function.
There is no string but String in Java.
You make this.word equals to word then check if they are equal...
You don't need to do if/else to return a boolean: just do return x.equals(y); (not necessarily wrong, but that's a personal pet peeve...).
compareTo, the classical one, isn't equals, but returns -1, 0 or 1 depending if one object is lower, equals or higher than the other.
Revise your lessons... :-)
In your code, the method compareTo is static, so you can not use "this."
I suggest you'd better NOT make compareTo method static.

Categories

Resources