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
}
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
guys so I have this method that I am trying to construct, I am just having a hard time understanding the logic. This is the condition of the method:
public int search(String str) – search the list for parameter str.
Searches should work regardless of case. For example, “TOMATO” is
equivalent to “tomato.”
Hint: the String class has a method called
equalsIgnoreCase. If the string str appears more than once in the
ArrayList, return the first index where the string str was found or
return -1 if the string str was not found in the ArrayList.
This is what I have so far for my code, I am not sure if this is the right way to do it. My ArrayList is defined as words.
In order to solve this issue, I am thinking of using a foreach statement to iterate through the ArrayList then an If to check if the words match then return the Index value based on the match but I am getting error. The other confusion I am having is how do I only return the first Index value only. Maybe I am doing this wrong. Any help or direction is appreciated.
public int search(String str)
{
for(String s : words)
if(s.contains(s.equalsIgnoreCase(str)))
return s.get(s.equalsIgnoreCase(str));
}
The first answer unnecessarily has to search through the list of words to find the index once it has determined that the word is in the list. The code should be able to already know the index. This is the more efficient approach:
public int search(String str) {
int i = 0;
for (String s : words) {
if (s.equalsIgnoreCase(str))
return i;
i++;
}
return -1;
}
There is also the more classic approach...the way it might have been done before the enhance for loop was added to the Java language:
public int search(String str) {
for (int i = 0; i < words.size(); i++)
if (words.get(i).equalsIgnoreCase(str))
return i;
return -1;
}
You actually overcomplicated it a little bit
public int search(String str) {
for(String s : words) {
if(s.equalsIgnoreCase(str)) {
return words.indexOf(s);
}
}
return -1;
}
Since the return method will stop running more code in the function it will always return the first matching word.
You can use stream also to resolve this problem:
public boolean search(List<String> words, String wordToMatch)
{
Predicate<String> equalityPred = s -> s.equalsIgnoreCase(wordToMatch);
return words.stream().anyMatch(equalityPred);
}
So I've been trying to figure this out on my own for the past couple of hours but I'm stuck.
I have an array that has a list of a person's name, age, height (in cm). I want to create a method where I use only the person's name as a parameter and searches for the name in the array; if there is no matching name, return null.
Looks like this:
data = new data[50];
data[0] = new data("Dan", 23, 179);
data[1] = new data("David", 20, 180);
data[2] = new data("Sharon", 19, 162);
data[3] = new data("Jessica", 22, 160);
data[4] = new data("Nancy", 25, 164);
...
numberData = 30; // this is the number of people that are in this array so far
This is what I've been trying so far..
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name == data[i]) {
return data[i];
} else {
return null;
}
}
}
I know it isn't right, but I can't seem to find a solution. Any ideas?
array is referencing the Data class with name parameter so we should compare with name parameter not directly with reference of data and for string comparisons always go for equals() method.
public Data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
Since you want to compare strings you must use the equals method.
Here's an example of how can you use java 8:
public Data findData(Data[] datas, String name) {
return Arrays.stream(datas).filter(data -> data.getName().equals(name)).findAny().orElse(null);
}
In case the loop doesn't execute at least once, you're missing return value.
== compares references, equals compares Strings.
Return null just in case, there is no such element in the array.
Class names should start with a capital letter. Please write Data instead of data.
Code:
public Data findData(String name) {
for (Data d : data) {
if (name.equals(d.getName())) {
return d;
}
}
return null;
}
is what you're looking for. In the original code, null was returned if the 0th element wasn't name.
OK, the above was a quick fix and now some theory:
The pseudo code for linear search in an array:
Loop through all elements in an array. If any matches with the one you're looking for, return it.
If nothing was returned, return the indicating value (null in our case).
Look, in the original code, on the 0th element, you decided whether to return that element or a null. Also, if the loop wasn't run at least once, there was no return statement to hit.
Use equals() to compare strings,
e.g.
if(name.equals(data[i].getName())) {
statements...
}
You should use equals() to compare strings. equals() checks the actual contents of the string, == checks if the object references are equal.
And also, as mentioned above, move return null outside the loop;
You can use following code. Assuming that your data class will have getName() method which returns the name value.
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
move the return null statement out of the loop.
Oh! and yes, use the equals() method instead of ==
I keep getting this error with my code. I can't seem to find the problem.
I'm not sure what to do because I even looked in the text book and it gives me a similar method except with different variables.
I'm on BlueJ.
public int findFirstOfPlayer(String searchString)
{
int index = 0;
boolean searching = true;
while(index < cards.size() && searching) {
String cardname = cards.get(index); // Error highlights index
if(cardname.contains(searchString)) {
searching = false;
}
else {
index++;
}
if(searching) {
return -1;
}
else {
return index;
}
}
}
Here is the problem, and if you used something like Eclipse or Idea, it would even highlight it for you.
String cardname = cards.get(index);
Obviously, cards is not compatible with String, you can't just assign it that way, because your collection card is probably not of type String aka ArrayList<String> cards
You can do either:
String cardname = cards.get(index).toString();
or
String cardname = String.valueOf(cards.get(index));
Given that Card is a class on its own you can't compare it to string. You have to either implement a method that returns a string you can compare with searchString or use a variable within the card object for the comparisson.
Something like this:
String cardname = cards.get(index).toString();
Or
String cardname = cards.get(index).name
I have a recursive method that reversed a string (HW assignment, has to be recursive). I did it....but its only returning the value of the string after the first pass. By analyzing the output after each pass i can see it does do its job correctly. heres my code, and the output i get below it:
String s = "Hello, I love you wont you tell me your name?";
int k=0;
public String reverseThisString(String s) {
if(k!=s.length()) {
String first =s.substring(0,k)+s.charAt(s.length()-1);
String end = ""+s.substring(k, s.length()-1);
k++;
s=first+end;
System.out.println(s);
this.reverseThisString(s);
}
return s;
}
output:
?Hello, I love you wont you tell me your name
I think you need to change this:
this.reverseThisString(s);
to this:
return this.reverseThisString(s);
otherwise the result of the method call is simply discarded.
I would also recommed that you change k to be a parameter to the method rather than a member.
Like Mark said, you forgot the return statement.
Also, there is an easier way to reverse a string (which is my current homework too :P )
public String reverse(String s) {
if(s.length() <= 1)
return s;
return reverse(s.substring(1))+s.charAt(0);
}