need to create a int length() method where the array is outside of the method . Was thinking of doing a for loop for (int i = 0; i < array.length; i++)…but im not sure help please. on API it looks easy but the array is not in the method itself so idk how to do it.
public class MyString
{
private char[] array;
private int size;
private int max;
public MyString()
{
array = new char[25];
max = 25;
}
public void setString(String newString)
{
if(newString.length() > 25)
{
System.out.println("/nEnter a number equal or less than 25 " );
}
else
{
for(int i=0; i < newString.length(); i++)
{
array[i] = newString.charAt(i);
}
}
}
public String toString()
{
return new String(array);
}
public char charAt(int index)
{
return array[index];
}
public boolean contains(char ch)
{
for(char c: array)
{
if(c == ch) return true;
}
return false;
}
public int indexOf( char ch )
{
for (int i = 0; i < array.length; i++)
{
if (array[i] == ch)
{
return i; // Character found, return current index
}
}
return -1; // Character not found. Return -1
}
public int length()
{
I am not sure if I get your question completely right, but
should do it. An array in java has a
lengthmember which contains the array length.Note that this returns the
Array lengthwhich will always be 25 in the code from your question.If you want the String length, either use the approach from @Grisha, or use the size member which is already in your code but not used yet:
This would avoid a loop with linear complexity (length() would be O(1) and not O(n)).