Search a string array for a specific string. [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was hoping someone could help. Well I know how to use linear search to find a numerical value inside of an array. But now I want to learn how to search a string array for a string.
For example if I have a string array of students names how could I search the array to find a specific name inside that array?
If someone could write me a simple example since I'm new to Java still. Thank you, also is there a better way to search these kinds of things or linear search fine? :)

Use Arrays.asList() to wrap the array in a List. Then search in the List using contains() method:
String[] a= {"is", "are", "then"};
Arrays.asList(a).contains("are");
You can do using arrays also, but have to write some more lines of code. contains() method also does the linear search only.
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}

The code for Strings can be the same as for numerical values, except you should use the String class's equals(...) method instead of ==.
You should use equals(...) because it's possible for two different String objects to have the same characters. But == would be incorrect because they are different objects.
Examples comparison expressions:
myArray[i].equals(myString)
or
myString.equals(myArray[i])
Note: Be sure the part on the left side isn't null. Otherwise you will get a NullPointerException.

Related

Counting the repetition of an element of an array java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I need to count the frequency of an element in arrays.
I used the method
Collections.frequency(Arrays.asList(arr),element);
but I get zero all the times
any ideas ?!
If you are ArrayList consists of elements of custom type
example person bean, or employee object.
Make sure you have overridden equals() method and hash() methods
if you have not overridden these methods that Collection method wont work.
You need to give details about "arr" & element. However, I did came across this some time back when I tried to use an array of primitives such as int[], converting them to a List using Arrays.asList()
There is nothing like List of "int". An Integer would work however, Integer arr[] = {1,1,1,1,3,3,4,5,5,5,6};

stringoutofboundexception in java (due to long string) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am getting a StringIndexOutOfBoundsException for a long string. Basically the program is reading string from text file and for some reason i am getting error when I use long strings. For e.g. if use a=b+c or a=b or a=b+c-d*a this all works but when i put long strings such as "programming" or "javatutorial" this gives me a StringIndexOutOfBoundsException. At first I thought this was due to the fact that I am not checking whether or not x is empty but that is not the case this is occurring due to the length of the string itself. I would appreciate if someone could help.
while (scan.hasNext()) {
String x = scan.nextLine();
try
{
if(!x.isEmpty())
{
char ch=x.charAt(0);
s=String.valueOf(ch);
}
}
catch(StringIndexOutOfBoundsException siobe)
{
System.out.println("invalid input");
}
}
With the partial code you provided, all we can tell you is that the exception is being thrown because you are using the method:
String.charAt(int index)
on a String that does not have a character at the 'index'-th position.
For example, if String word = "cat", then word.charAt(8) would throw an exception because 'cat' only has three characters.
Search through your code for all the places that you used the charAt(int index) method and test that 'index' is indeed less than String.length(). Your error shows an argument of '11', so you can narrow your search to the location where you called the charAt() method with an index of 11. (This may be inside a loop).

String comparison is wrong [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have a little/huge problem with String comparison in Java, I want to compare two Strings and .equals([...]) does not give me the correct result.
I also tried the following: ==, .compareTo([...]), .trim(), .equalsIgnoreCase([...]), creating a Collator with default Locale and using [collator].compare.
(All fail to work)
The first String comes from an already created object (the content of the string is from a database), the second String comes from a newly created object (but has been passed to a method), the content of this String is from the same database.
I am pretty clueless what to do now, the last thing I'd try is to convert it to some number (i.e. hex).
I already tried to write both Strings to console and manually look for differences, but there is none...
Code is this:
public static Lagerplatz hinzufuegen(Lagerplatz lagerplatz) {
boolean neu = true;
if (lagerplaetze.isEmpty()) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " erstmalig hinzugefügt!");
}
for (int i = 0; i < lagerplaetze.size(); i++) {
System.out.println("'" + lagerplatz.getBezeichnung() + "'" + " - " + "'"
+ lagerplaetze.get(i).getBezeichnung() + "'");
if (lagerplatz.getBezeichnung().equalsIgnoreCase(lagerplaetze.get(i).getBezeichnung())) {
neu = false;
}
}
if (neu) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " hinzugefügt!");
}
return lagerplatz;
}
The if-part with (lagerplaetze.isEmpty()) does work, after the first one is added it should check if the Lagerplatz (at least the name of it) is already in the lagerplaetze-ArrayList, if so then don't add, if not add.
Stepping through it revealed that the objects are correctly referenced...
Thanks very much in advance, and sorry if this question has been answered already but I can't find a helping answer under all these questions...
EDIT1: Normalizing does not help in this case, "umlaute" (german ä, ö or ü) are not causing the problem...
Converting the String to a byte[] and converting this byte-array to String like:
(Arrays.toString(lagerplatz.getBezeichnung().getBytes()).equalsIgnoreCase(
Arrays.toString(lagerplaetze.get(i).getBezeichnung().getBytes())))
and then comparing it does also not solve the problem, the bytes of the two strings are exactly the same: '[72, 55, 48]' - '[72, 55, 48]'
EDIT2: The problem is not with the String comparison, it is because the variables of the class "Lagerplatz" are static, they were replaced each time the loop is entered...
Maybe delete this question?
The only time two strings that look exactly the same but equals() does not result in true is when the unicode composition is different.
For example one can compose the A umlaut (Ä) with a single character: \u00C4
Or with a combination of the A character and the dots (the dieresis character ¨): \u0041\u0308
In essence, you are using two unicode characters for one letter. Because equals() compares characters, the form with dieresis is not equals to the form without.
To overcome this problem, one must decompose each string to a canonical form before comparison.
In Java one can create such a canonical form like this:
java.text.Normalizer.normalize("Your String", java.text.Normalizer.Form.NFD);
Once normalized, equals() will work as expected.
Obviously, since you didn't provide any data, this answer may or may not match your problem.
In any case, you might want to normalize all Strings in some form and then use a Set as data structure, not a list.

NullpointerException while reading a json with null value for array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Is there a way to read this json without causing nullpointer exception through jackson.
{
"years": [
null
]
}
years is an array of String
Also is that a valid format of json when there are no years?
If you look closely at the tutorials for Jackson, you will see that the JSON this library produces itself for empty arrays uses this notation: { "empty" : [ ]}
Therefore you may try replacing any singular null value in an array with just an empty array before sending your JSON to Jackson, it should accept without throwing any exceptions.
Canonically, a ' null' member of an array is actually valid JSON syntax. See also http://en.wikipedia.org/wiki/JSON. Members of an array can be of any type, thus they can be:
Strings
Numbers
Booleans
Arrays
Objects
null
For your usage scenario however, I would recommend using the empty array instead, because it is simply far easier to program with. For example, consider a usage case where you call some function f() on each of your 'years' which wants an integer input. Code like
foreach(x in array){f(x);} will fail because you will call f() with a 'null' type instead of an integer, causing errors. If you instead used the empty array, the correct behaviour will happen without having to treat the case where there are no years diffrently by explicitly looking for the null. Just makes your life easier that way.

Return True if Arrays have same elements [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I could use some help comparing two arrays, previously created in another method. They are called enterNumbers, user input array and drawNumbers, a randomly generated array.
My method header should look like this:
public static boolean containSameElements(int[] enterNumbers, int[] drawNumbers)
{
}
The method should compare the two arrays and return true if the numbers are the same, regardless of the order.
Not looking for the answer, just maybe a place to start.
Just sort them before
Arrays.sort(enterNumbers);
Arrays.sort(drawNumbers);
if(Arrays.equals(enterNumbers, drawNumbers)){
System.out.println("both are same");
}
Well, you can either
Create two histograms (using a hash based map/set) to count elements
in each array, and then compare the sets/maps. This solution is O(n)
space and O(n) time on average. Have a look at Map or Set for this. (Either you want Map or Set depends if existence of duplicates is important or not)
Another solution is sort and iterate. This is O(nlogn) time worst
case. Have a look on Arrays.sort() for this solution.
if (drawNumbers.length != enterNumbers.length)
return false;
List<Integer> base = new ArrayList<Integer>();
for (Integer i : drawNumbers)
base.add(i);
for (Integer i : enterNumbers)
base.remove(i);
return base.isEmpty();
This is a very common "problem" which can be solved using different methods. If I understand you correctly, all of the numbers have be inside the both arrays, but they don't have to be at the same indexes?
Then you can just make a while/for loop with (with two counters; one for each array) and check if the number on index 0 in the first array equals any of the numbers in the second array. If it doesn't the while/for-loop is done and the test failed. If it does go on to the next index in the first array. Continue until everything is tested(all numbers in first array versus the second array) or until a number doesn't exist in both arrays. Good luck

Categories