How to create a simple indexOf() method of my own - java

I'm trying to create a simple indexOf() method that returns an int value and that recognizes a string (not char) of an string array.
public int indexOf(String str) {
/*Getting and return the index of the first
*occurrence of the specified String. Return
*-1 if string not in the list
*/
for(int i = 0; i < listArray.length; i++) {
if(listArray[i].equals(str)) {
return str.indexOf(listArray[i]);
}
}
return -1;
}
I'm using indexOf() method from Java for the first return, but it always returns 0. Why is this, and is there a better way to write this method?

Your for-loop is fine, the problem there is that when you find it, you are returning the index where the string is in itself, and that will always be 0.
For instance, "hello" is in the position 0 for the string "hello".
You should just return i, like this:
public int indexOf(String str) {
/* Getting and return the index of the first
* occurrence of the specified String. Return
* -1 if string not in the list
*/
for (int i = 0; i < listArray.length; i++) {
if (listArray[i].equals(str)) {
// If we get here, it means that the item for position `i` is equal to `str`.
return i; // just return `i`
}
}
return -1;
}

return i; by definition listArray[i] is equal to str.

Because, whenever you run return str.indexoOf(listArray[i]);, you already have str equals listArray[i]. Of course you are getting 0 all the time, it's equivalent to str.indexOf(str);
And you really don't need to do that. You have already found an element in the list that equals the given string, just return its location:
return i;

You must return i (index) when the if condition is satisfied.
public int indexOf(String str) {
for(int i = 0; i < listArray.length; i++) {
if(listArray[i].equals(str)) {
return i;
}
}
return -1;
}

I think you have got confused. if you want to find a string from ArrayList and if you have already found the string in your if(listArray[i].equals(str)) then all you have to do is just return that index i as you have already found it.
for(int i=0;i<listArray.length;i++){
if(listArray[i].equals(str)){
return i;
}
}
is the answer.
Always remember: If you even post the contents or sample of your listArray and sample string to find in it... It will help us better to understand where exactly you are stuck

You can do this using a for loop.
Check if the string matches using equals.
If yes, return the index.
If you come out of the for loop, return -1.

public int indexOf(String iparam){
String astring = "" //YOUR OWN STRING
boolean astat = false;
List<Integer> alist = null;
for(int i=0; i<astring.toCharArray().length; i++){
alist = new ArrayList<>();
for(int j=0; j<iparam.toCharArray().length; j++){
try{
if(astring.toCharArray()[i+j] == iparam.toCharArray()[j]){
alist.add(i+j);
}else{
break;
}
}catch(Exception ex){
ex.printStackTrace();
break;
}
}
if(alist.size() == iparam.toCharArray().length){
astat = true;
break;
}
}
if(astat){
return alist.get(0);
}else{
return -1;
}
}

Related

Matching value with ArrayList?

I'm fairly new to java and have started on ArrayLists and I'm stuck on a particular issue.
What I'm trying to do in the code below is have a value passed to the method locateCatalogue, which will go through the array list collection to match the value entered.
Once it finds the matched value, stop executing and show how many items there are for the said item. Otherwise if the number doesn't exist just return null, Here's my code:
Arraylist<Catalogue> items;
Public locateCatalogue (int number)
// if int number matches value entered, find number.
for(int i=0; i < locateCatalogue.length; i++)
if (Catalogue.get(i) = number)
return Catalogue;
}
else {
//return no value if entered value has no matching number.
return null;
}
the operator =means to define variables. For comparison use ==. Furthermore you messed up the if statement:
Arraylist<Catalogue> items;
Public int locateCatalogue (Catalogue catalogue ){
for(int i=0; i < items.size(); i++)
if(items.get(i) == catalogue )
return i;
else
return -1;
}
But you can not count the items you want if you return after you found the first. Also it's not clear what you want to return
The syntax for the for-loop is as follow:
for(int i=0; i < items.size(); i++) {
//some code
}
The syntax for the if-statement is:
if(items.get(i) == number) {
//some code
}
public Catalogue locateCatalogue( int number ) {
for( Catalogue item : items ) {
if( item.id == number ) {
return item;
}
return null;
}

Taking a long string of numbers and removing any zeroes in front of it, then returning that altered string (in Java)

So I have a public static method 'getWithoutLeadingZeroes', which gets passed a String and simply needs to return it without any zeroes prefixing the string of numbers.
Now, I know that I need to iterate through the string until I find the first non-zero char in the string, but I'm not exactly sure how to take the point where the method finds the non-zero char and start copying the remainder of the String into a new String, then returning it.
Here's what I have so far:
public static String getWithoutLeadingZeroes(String s) {
boolean notZero = false;
char[] t = new char[x];
for(int i = 0; i<s.length(); i++){
if(s.charAt(i) == 0){
notZero = false;
} else {
notZero = true;
}
if(notZero = true){
for(int j = index.charAt(i))
}
return ""; //to be completed
}
I created a boolean variable to stop the loop once it hits the non-zero char and I'm pretty positive the first half of the code is accurate, but its the creating of the new String to be returned that I'm a bit stuck on. Any suggestions would be welcome.
You are NOT stopping your loop.
You could do that using the break keyword.
And: your comparison is wrong, it should read
if (... == '0'
You could use String#substring(int beginIndex) instead:
public static String getWithoutLeadingZeroes(String s) {
int i = 0;
while (i < s.length() && s.charAt(i) == '0') i++;
return s.substring(i);
}
How about the following way?
public static String getWithoutLeadingZeroes(String s) {
while(s.startsWith('0'))
s = s.substring(1);
return s;
}
This should do it
String nmbrStr = "1001234";
String cleanedStr = nmbrStr; // this way the whole number will be
// returned if in has no leading zeroes
for (int i = 0; i < nmbrStr.length(); i++) {
if (nmbrStr.charAt(i) != '0') {
cleanedStr = nmbrStr.substring(i);
break;
}
}
System.out.println(cleanedStr);
You can also use Integer.parseInt(nmbrStr) which is a lot cleaner
A simple solution.
public static String getWithoutLeadingZeroes(String stringOfNumbers) {
return String.valueOf(Long.parseLong(stringOfNumbers));
}
Another alternative solution:
public String getWithoutLeadingZeroes(String str) {
int from = 0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == '0'){
from = i;
}else{
break;
}
}
return str.substring(from+1);
}
You can then make it a little bit more robust by implementing try/catch blocks and possibly along with cases that deal with unexpected input e.g null parameter or a zero-length string etc.

In Java, how can I test if an Array contains the same value?

I'm looking for a method to detect if all objects within an array(list) are the same.
e. g:
arraylist1 = {"1", "1", "1", "1"} // elements are the same
arraylist2 = {"1", "1", "0", "1"} // elements are not the same
Thanks for help
Java 8 solution :
boolean match = Arrays.stream(arr).allMatch(s -> s.equals(arr[0]));
Same logic for lists :
boolean match = list.stream().allMatch(s -> s.equals(list.get(0)));
It comes quite complicated if there are only or any null values in the array (resulting in a NullPointerException). So possible workarounds are:
Using Predicate.isEqual, it uses the static method equals from the Objects class and it will do the null check for you before calling equals on the first argument.
boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
Using distinct() and count() :
boolean match = Arrays.stream(arr).distinct().count() == 1;
that can be improved into Arrays.stream(arr).distinct().limit(2).count() == 1; as there is no need to check the all pipeline's content if you already find 2 distinct elements.
public static boolean AreAllSame(String[] array)
{
boolean isFirstElementNull = array[0] == null;
for(int i = 1; i < array.length; i++)
{
if(isFirstElementNull)
if(array[i] != null) return false;
else
if(!array[0].equals(array[i])) return false;
}
return true;
}
Please feel free to correct any syntax mistakes. I fear my Java-fu may be lacking today.
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
// All the elements are the same
}
If your list is empty return true.
If not, loop through it and check if all elements are equal to the element at index 0.
If so, return true, otherwise return false.
public boolean containsSameValues(int[] array) {
if(array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
int first = array[0];
for(int i=0;i<array.length;i++) {
if(array[i] != first) {
return false;
}
}
return true;
}
boolean containsAllValues=false;
boolean t=false;
int isto=0;
for(int k=0;k<arraylist1.size();k++){
for(int n=0;n<arraylist2.size();n++){
if(arraylist1.get(k).equals(arraylist2.get(n))){
t=true;
}
}
if(t){
isto++;
}else{
isto=0;
break;
}
}
if(isto!=0){
containsAllValues=true;
}
With this you can check if arraylist2 contains values from arraylist1.
You can sort the array and then use the Array equals method:
public boolean equalArrays(int []f ,int [] g){
Arrays.sort(f);
Arrays.sort(g);
if (Arrays.equals(f, g))
return true;
return false;
}
To test it out:
int [] h={1,1,0,1};
int [] t={1,1,1,0};
System.out.println(cc.equalArrays(h,t));
For Java 8, Alexis C's solution is probably the best. However, if you're stuck with <= Java 7 and don't think David Wallace's approach is expressive enough, you could also try this:
boolean result = Collections.frequency(yourList, "1") == yourList.size();
Basically what this does is that it checks whether the number of elements in your list equal to "1" matches the total number of elements in the list. Pretty straightforward.
By the way -- this is pure Java Collections API, and I believe Collection.frequency(..) has been there since at least JDK 1.5. See the javadocs for more information.
EDIT: Here's a quick fiddle if you want to take this for a test drive.
The easiest one:
public static boolean checkTheSame(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] != numbers[i + 1]) {
return false;
}
}
return true;
}

variable type question java

So here is my problem im trying to search an array for a value and then return the index as well as the string name.
But my problem is that when i return the index it sets it as a string because thats what the method called for so when i try to type cast the index to be changed to a string my compiler throws errors. Here are the trouble some methods, i can post my whole code if you guys would like to see it.
public static String studentGrade(Scanner stdIn)
{
System.out.print("What student do you want to enter a grade for?");
String searchName=stdIn.next();
String index = findStudent(students, searchName);
int studentId =(int) currentStudentId(students, searchName);
if (index == searchName)
{
System.out.println("Student was found, " + index + studentId);
System.out.println("What is the grade that you want to input for this student?");
String input = stdIn.next();
String studentGrade = input;
return studentGrade;
}
else
{
System.out.println("not found");
}
}
public static String findStudent(String[] students, String searchName)
{
for (int i = 0; i < students.length; i++)
{
if (students[i].equals(searchName))
{
String currentStudentId = i;
return currentStudentId;
return searchName;
}
} // end for
String fail = "fail";
return fail;
} // end findStudent
I don't believe returning both String and index as int is a good idea. Why don't you just return index and get the student by looking up in array that contains all students.
If the student wasn't found you can return for example -1.
This is what I mean:
String[] students = new String[] { ... };
//...
int indexFound = findStudent(students, "John Doe");
if (indexFound >= 0) {
String studentFound = students[indexFound];
}
PS. Your code contains errors (like doubled return command)
Why would you want to return searchName from findStudent() to a method that passes it through an argument.
Of course the caller method already has the value. Just return the index:
Example:
public static int findStudent(String[] students, String searchName)
{
for (int i = 0; i < students.length; i++)
{
if (students[i].equals(searchName))
{
return i;
}
} // end for
int fail = -1;
return fail;
} // end findStudent
An index is naturally an int, not a String. You should return an int.
Assuming this is homework, and you have to return a String, you can convert a number into a String using the following.
return ""+currentStudentId;
However, the problem you have is that you are trying to return two values.
I suspect you have mis-understood the requirements, I suggest you read them again.
A shorter example, using varargs
public static int findString(String string, String... strings) {
for (int i = 0; i < strings.length; i++)
if (strings[i].equals(string))
return i;
return -1; // for not found.
}
Or even the following works for any type.
public static <T> int indexOf(T t, T... ts) {
for (int i = 0; i < ts.length; i++)
if (ts[i].equals(t))
return i;
return -1; // for not found.
}
e.g.
int found = indexOf(5, 1,3,5,7); // found = 2;

Checking if one array is the reverse of another array in java

Im trying to create a method that take 2 int array as the input parameter and returns true if the array are reverse and false otherwise. This is what I have so far but it is wrong.
public static void main(String[] args)
{
int b,a;
int[] data1 = {14,-70,-18,88,85,97,-65,13,-71,-12};
int[] data2 = {-12,-71,13,-65,97,85,88,-18,-70,14};
boolean check = true;
for (a=0;a<data1.length;a++)
{
for (b=data2.length-1;b>=0;b=b-1)
{
if (data1[a] != data2[b])
check=false
}
}
System.out.println(check);
}
My example is suppose to print true but it doesn't.I am assuming the 2 arrays are of the same length. Can anyone help?
You don't need two loops - you only need to loop once, using the index "normally" in one array, and from the other end for the other array:
public static boolean checkReversed(int[] x, int[] y)
{
// For production code, possibly add nullity checks here (see comments)
if (x.length != y.length)
{
return false;
}
// Loop through x forwards and y backwards
for (int i = 0; i < x.length; i++)
{
if (x[i] != y[y.length - 1 - i])
{
// As soon as we've found a "mistake" we can exit:
// This is simpler (IMO) than keeping a "check" variable
return false;
}
}
return true;
}
You can try doing:
// compare the length.
check = (data1.length != data2.length)?false:true;
// if lengths are equal..go ahead and compare elements in reverse.
if(check) {
for(int i=0,j=data2.length;(i<data1.length) && (j>=0);i++,j--) {
// if you find a mismatch..set check to false..and break
// no need to compare other ele.
if(data1[i] != data2[j]) {
check = false;
break;
}
}
}
in this, both array length should be equal. then
for(int i=0,j=array.length;i<array.length,j=0;i++,j--){
write your comparison logic here
}
Your code actually compares every element in data1 with every element with data2 and prints false if there is any one mismatch. That is not what you intend it to do.
here is an answer to your question in a complete .java file
//yeah.java
public class yeah {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] data1 = {14,-70,-18,88,85,97,-65,13,-71,-12};
int[] data2 = {-12,-71,13,-65,97,85,88,-18,-70,12};
System.out.println(isReverse(data1, data2));
}
public static boolean isReverse(int[] a, int[] b)
{
if (a.length != b.length) //If a and b are not of the same length how can they be reverse?
return false;
for (int i=0;i<a.length;i++)
if (a[i] != b[a.length-i-1])
return false;
return true;
}
}
Just a quick note about method and functions.. As soon as you discover that they are not reversed, you should exit using a return statement.. no need to keep on computing..
You can do it in one loop, you don't need two.
for (int i=0,j=end;i<end;i++,j--)
This can be done in a single loop there is no need for two loops.
For example:
for (int i = 0, j = last; i < last; i++, j--)

Categories

Resources