toString method with adjustable Array size - java

Every source I've looked at I either don't understand, doesn't seem to apply, or uses something like an Array list. I'm not familiar with those. So I'd like to use a basic toString method that prints out the index of the array as well as the number held when compared to the variable 'length' -- num.length could be different as that's the physical size of the underlying array. The for loop at the bottom has the gist of it. I'm trying to print out the index (0-infinite) with int's that are held in the resizeable array. The variable 'length' is not the actual size of the array but a working size that contains 0 until another cell is added. The 'strang' variable is just something I've tried. I don't think it will work, but anything else I doesn't seem to help as I'm stuck.
public class XArray
{
private int[] nums;
private int length;
public XArray()
{
nums = new int[10];
length = 0;
}
public void add(int value)
{
if (length == nums.length)
{
int[] nums2 = new int[(int)(nums.length * 1.2)];
for ( int i = length - 1; i >= 0; i-- )
{
nums2[i] = nums[i];
}
nums = nums2;
}
nums[length] = value;
length++;
}
public void set(int index, int value)
{
if (index < length)
{
nums[index] = value;
}
}
public int get(int index)
{
return nums[index];
}
public int size()
{
return length;
}
public void remove()
{
nums[length - 1] = 0;
length--;
}
public String toString(int[] nums)
{
String strang = "l";
for ( int i = 0 ; i < length; i++ )
{
strang = "Index: " + i + " Number: " + nums[i] + ", ";
}
return strang;
}
}

You need to concatenate the values on each iteration of the loop...something like...
public String toString(int[] nums)
{
StringBuilder strang = new StringBuilder(length);
for ( int i = 0 ; i < length; i++ )
{
strang.append("Index: ").append(i).append(" Number: ").append(nums[i]).append(", ");
}
return strang.toString();
}
Generally speaking, toString should't take parameters, there would a difference between nums and length which could cause issues
#Override
public String toString() {...
This way, you will be printing the contents of the objects num array, which is contextually associated with length

You probably meant to use += instead of = in that method (though many people will tell you to use a StringBuilder because successive concatenations, if not optimized by a compiler` will generate a lot of garbage).
Also, don't pass in nums! You want to use the field nums; passing in an argument will use the argument. The real toString has no parameters (and should have an #Override annotation).

Related

How to execute class method in a Java program? [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 10 months ago.
Improve this question
In this code, we have to add a method set() which will take two parameters, an int index, and an Integer value, which will set the array element at the specified index to the specified value and the array will grow if an attempt is made to set a value beyond the end of the array by using the method resize().
This is the code I currently have:
public class MyVector {
protected Integer[] internalArray;
public MyVector( int initialSize )
{
internalArray = new Integer[initialSize];
}
public void resize( int newSize )
{
if ( newSize != internalArray.length ) {
Integer[] newArray = new Integer[newSize];
for (int i=0; i < Math.min(newSize,internalArray.length); i++)
newArray[i] = internalArray[i];
internalArray = newArray;
}
}
public Integer get( int index )
{
if ( index < internalArray.length )
return internalArray[index];
return null;
}
public static void main(String[] args)
{
MyVector vec = new MyVector(5);
for ( int i = 0 ; i < 20 ; i++ )
vec.set(i, i*i );
for ( int i = 0 ; i < 20 ; i++ )
System.out.println( "Element" + i + "=" + vec.get(i) );
}
}
This is the current set()-method I have made. I am not quite sure how to use or execute the set() method. How should I proceed?
public int set(int a, int b){
a = b;
if (b>19){
resize(b);
}
return a;
}
Welcome to stackoverflow! I have a feeling this is a homework question, if it is - please try to do your homework on your own since it will greatly assist you in the future.
As you can see in the code you have provided there is currently no function set() for your MyVector class.
In order to make a set() function you have to declare it. This w3schools guide will most likely explain the basics for you: https://www.w3schools.com/java/java_encapsulation.asp
For your code that could be:
public void set(int index, int value) {}
Assuming you don't want a return value from the function.
Then you can just change the value of the array to what you want it to be:
public void set( int index, int value ) {
internalArray[index] = value;
}
More information if you are interested:
What is an interesting point is that many people discuss the reasoning behind why we in OOP should need a use for setters and getters. In your example it seems like you only want your list to be of size = initialSize which you set to 5. What if someone inputs an index higher than 5? What if they input 10 instead? What will your list look like? If you want to limit those things you can in your set() function add limits to the values and indexes acceptable (which from an OOP standpoint) might be a better idea.
As I tried to explain there might be occasions where you would want to handle events when the index goes beyond. This is an example of what set() can look like if you want to increase the array size if the index is out of bounds. I really suggest you look into array and deep copying though.
public void set( int index, int value ) {
if (index > internalArray.length - 1) {
Integer[] newInternalArray = new Integer[internalArray.length + 1];
for(int i = 0; i < internalArray.length; i++) {
newInternalArray[i] = internalArray[i];
}
newInternalArray[newInternalArray.length-1] = value;
internalArray = newInternalArray;
} else {
internalArray[index] = value;
}
}
Or by using the resize() function:
public void set( int index, int value ) {
if (index > internalArray.length -1) {
resize(index + 1);
}
internalArray[index] = value;
}
With this solution you may consider to make the resize() private unless you want others to call it publicly. This is what can be so interesting and what I tried to tell you. By making it private and using it in the set-method you allow for setting values but you are in charge of how the values are changed.
Your vector class contains an internal array. There you have to modify the value at the given position. If the given position is outside of the array then you can use the resize method to enlarge the internal array:
public class MyVector {
protected Integer[] internalArray;
public MyVector( int initialSize )
{
internalArray = new Integer[initialSize];
}
public void resize( int newSize )
{
if ( newSize != internalArray.length ) {
Integer[] newArray = new Integer[newSize];
for (int i=0; i < Math.min(newSize, internalArray.length); i++)
newArray[i] = internalArray[i];
internalArray = newArray;
}
}
public Integer get( int index )
{
if ( index < internalArray.length )
return internalArray[index];
return null;
}
public void set( int index, int value )
{
if (index > internalArray.length -1) {
resize(index + 1);
}
internalArray[index] = value;
}
public static void main(String[] args)
{
MyVector vec = new MyVector(5);
for ( int i = 0 ; i < 20 ; i++ )
vec.set(i, i*i );
for ( int i = 0 ; i < 20 ; i++ )
System.out.println( "Element" + i + "=" + vec.get(i) );
}
}
$ java MyVector.java
Element0=0
Element1=1
Element2=4
Element3=9
Element4=16
...
Element17=289
Element18=324
Element19=361

How to merge two sorted arrays in Java?

I'm trying to create a third sorted array, c, from the two previously created arrays, a and b; however, I'm getting several errors within the merge method that say "The type of the expression must be an array type but it resolved to OrdArray". I've been at it for hours already, and feel like my brain is mush now. Can someone help me out?
class OrdArray
{
private long[] a; // ref to array a
private int nElems; // number of data items
//-----------------------------------------------------------
public OrdArray(int max) // constructor
{
a = new long[max]; // create array a
nElems = 0;
}
//-----------------------------------------------------------
public int size()
{ return nElems; }
//-----------------------------------------------------------
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;
while (true)
{
curIn = (lowerBound + upperBound ) / 2;
if (a[curIn] == searchKey)
return curIn; // found it
else if (lowerBound > upperBound)
return nElems; // can't find it
else // divide range
{
if (a[curIn] < searchKey)
lowerBound = curIn + 1; // it's in upper half
else
upperBound = curIn - 1; // it's in lower half
} // end else divide range
} // end while
} // end find()
//-----------------------------------------------------------
public void insert(long value) // put element into array
{
int j;
for (j = 0; j < nElems; j++) // find where it goes
if (a[j] > value) // (linear search)
break;
for (int k = nElems; k > j; k--) // move bigger ones up
a[k] = a[k-1];
a[j] = value; // insert it
nElems++; // increment size
} // end insert()
//-----------------------------------------------------------
public boolean delete(long value)
{
int j = find(value);
if (j == nElems) // can't find it
return false;
else // found it
{
for (int k = j; k < nElems; k++) // move bigger ones down
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
} // end delete()
//-----------------------------------------------------------
public void display() // displays array contents
{
for (int j = 0; j < nElems; j++) // for each element,
System.out.print(a[j] + " "); // display it
System.out.println("");
}
//-----------------------------------------------------------
public static long[] merge(OrdArray a, OrdArray b)
{
long[] c = new long[a.nElems + b.nElems];
int i = 0, j = 0, k = 0;
while (i < a.nElems && j < b.nElems)
{
if (a.data[i] < b.data[j])
c[k++] = a.data[i++];
else
c[k++] = b.data[j++];
}
while (i < a.nElems)
c[k++] = a.data[i++];
while (j < b.nElems)
c[k++] = b.data[j++];
return c;
}
} // end class OrdArray
////////////////////////////////////////////////////////////////
class OrderedApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
OrdArray a, b, c; // reference to array
a = new OrdArray(maxSize); // create the array
b = new OrdArray(maxSize);
c = new OrdArray(maxSize);
a.insert(11);
a.insert(13);
a.insert(15);
a.insert(17);
a.insert(19);
a.insert(21);
a.insert(23);
a.insert(25);
a.insert(27);
a.insert(29);
b.insert(12);
b.insert(14);
b.insert(16);
b.insert(18);
b.insert(20);
b.insert(32);
b.insert(24);
b.insert(26);
b.insert(28);
b.insert(30);
OrdArray.merge(a,b);
System.out.print("Array a: ");
a.display();
System.out.println();
System.out.print("Array b: ");
b.display();
System.out.println();
System.out.print("Array c: ");
c.display();
System.out.println();
} // end main()
}// end class OrderedApp
OrdArray is not an array type (despite the name); therefore, you can't index it like an array. This expression
a[i++]
where a is an OrdArray, will have no meaning. Java doesn't give you a way to define your own [] operator for classes (unlike C++). Therefore, you'll have to add a method to OrdArray to return the element at a given index, something like
public long get(int index) { ...write the code... }
a.get(i++) // will then get the element at that index
Although I'm not sure this is what you want, since you've declared c to be an int[] and the array in OrdArray to be a long[], so I'm not sure what you're trying to do.
EDIT: After reading your comment, I realized that the merge method is inside the OrdArray class. I missed that before. Since that's the case, you don't need to add a get method; you can access the private fields of your OrdArray parameters directly. In your method:
public void merge(OrdArray a, OrdArray b)
you want to get at the private array a that you declare for each OrdArray. If you just use a, the variable will refer to the OrdArray, which isn't an array (as described above); to get at the long[] a belonging to the OrdArray a, you need to say
a.a[i++]
and likewise, for b,
b.a[i++]
This can look confusing to a reader, so I suggest coming up with a better name so that you're not calling two things a. Perhaps data?
A couple other things: You use merge like this: c.merge(a,b), which means that merge is an instance method and c is the instance you're operating on. But your method doesn't do anything with the current instance. (The c you declare in merge is a local variable that has nothing to do with the c you use when calling merge.) Right now, your method is going to a lot of trouble to construct the local array c, but then it just throws it away. You either need to (1) fix the method so that it sets up the a (or data) array in the current instance; or (2) make it a static method and make the method return the new array as a function result. I'm not sure which one your instructor wants you to do.
I'm not exactly sure what you are trying to do. But to resolve error, i have corrected the articular block.
To note, OrdArray class is not an array. It's a class that has a long[] a. So you need to get the array like any other property from the object.
For betterment, please change the method signature like this:
public void merge(OrdArray ordArr1, OrdArray ordArr2) {//Note parameters' name change
.
.
.
while (i < ordArr1.nElems && j < ordArr2.nElems)
{
if (ordArr1.a[i] < ordArr2.a[j]) //should resolve
c[k++] = ordArr1.a[i++];
else
c[k++] = ordArr2.a[j++];
}
while (i < a.nElems)
c[k++] = ordArr1.a[i++];
while (j < b.nElems)
c[k++] = ordArr2.a[j++];
}
If you accept solution wit Lists it would be:
List<Integer> result = new ArrayList<Integer>(Arrays.asList(sourceArray));
result.addAll(Arrays.asList(secondSourceArray));
Collections.sort(result);
You can optionally convert it back to array with
result.toArray();
I am confused why you are using binary search. Simple way is to insert two arrays using two insert methods or one. Using a merge method, just merge those two already sorted arrays by comparing the least element among two sorted arrays.
Remove delete, search etc methods, they are not required.
This is my code. I have inserted two integer arrays(elements) into inserta() and insertb() sorted them and merged them using insert() method. Finally I have this sorted array after merging them. Please see my code here:
package sample;
/**
*
* #author Shivasai
*/
public class Merge {
int i;
int j;
int k;
int n;
int m;
int p;
private long[] a;
private long[] b;
private long[] c;
public Merge()
{
a=new long[10];
b=new long[10];
c=new long[100];
n=0;
m=0;
p=0;
}
void inserta(long key)
{
for(i=0;i<n;i++)
{
if(a[i]>key)
break;
}
for(j=n;j>i;j--)
{
a[j]=a[j-1];
}
a[j]=key;
n++;
}
void insertb(long value)
{
for(i=0;i<m;i++)
{
if(b[i]>value)
break;
}
for(j=m;j>i;j--)
{
b[j]=b[j-1];
}
b[j]=value;
m++;
}
void insert()
{
i=0;
j=0;
while(i>n || j<m)
{
if(a[j]<b[i])
{
c[p]=a[j];
j++;
p++;
}
else
{
c[p]=b[i];
i++;
p++;
}
}
}
void displaya()
{
for(k=0;k<10;k++)
{
System.out.print("," +a[k]);
}
System.out.println();
}
void displayb()
{
for(k=0;k<10;k++)
{
System.out.print("," +b[k]);
}
System.out.println();
}
void displayc()
{
for(k=0;k<20;k++)
{
System.out.print("," +c[k]);
}
}
public static void main(String[] args)
{
Merge obj = new Merge();
obj.inserta(25);
obj.inserta(12);
obj.inserta(1800);
obj.inserta(9);
obj.inserta(10);
obj.inserta(15);
obj.inserta(18);
obj.inserta(19);
obj.inserta(0);
obj.inserta(1500);
obj.insertb(36);
obj.displaya();
obj.insertb(2);
obj.insertb(3);
obj.insertb(2000);
obj.insertb(5);
obj.insertb(6);
obj.insertb(7);
obj.insertb(8);
obj.insertb(21);
obj.insertb(85);
obj.displayb();
obj.insert();
obj.displayc();
}
}

How to add to array without ArrayIndexOutOfBoundsException?

Can anyone answer this question?
public class AddingArray {
public static void main(String[] args){
int arry1[] = {2,3,4,5,6,7,9};
int arry2[] = {4,3,7,9,3,5};
for(int i = 0; i <arry1.length; i++){
int result = arry1[i] + arry2[i];
System.out.println("Result "+result);
}
}
}
Whenever I try executing the above code I get the error Exception in
thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at
basics.AddingArray.main(AddingArray.java:9)
But,my output should be like this 6,6,11,14,9,12,9
As people have mentioned, one of yours arrays is literally shorter than the other. Take two blocks and overlay them over only one block. The second (in this case index 1 block) would fall into the abyss, because the block that was supposed to catch it never existed.
I would make sure both of them are of the same size. If you do want to leave em as they are, I would do this:
int result = 0;
try
{
for(int i = 0, length = array2.length; i < length; i++)
{
result = array1[i] + array2[i];
System.out.println("Result is: " + result);
}
catch(Exception e)
{
System.out.println("You tried to do something that resulted in an error");
System.out.println("Your previous result was: " + result);
}
}
SO, assuming that I still recall how to do basic arrays, what this code will do is that it will catch any errors thrown by your code.
Let's make this as simple and understandable as possible, with no fancy annotations:
You have two int arrays, of not equal lengths, and you wish to add the index-paired numbers to an array of the sums. However, if one of the arrays does not have any more numbers, the value of the longest array will be the result.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
You need to determine the length of the longest array. You can do this with a Math.max()-method, where you give the length of each array as parameters:
int biggestArrayLength = Math.max(arry1.length, arry2.length);
Then, instead of for(int i=0;i<arry1.length;i++){, you write:
for(int i=0;i<biggestArrayLength;i++){
Now it doesn't matter which of the two arrays is the biggest one.
Inside the loop, I would define two ints, representing a value from each of the two arrays:
int value1 = arry1[i];
int value2 = arry2[i];
however, this will give an error when the smallest array does not have any more elements. We need to check if the array actually has an element with index i. index numbers in arrays start with 0. so if the length is 7, the 7 elements will have index numbers from 0-6. In other words, only index numbers that are lower (and not equal) to length, is valid numbers:
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
System.out.println("Result "+result);
}
}
}
Now, if you need to put these in a third array, say named sumArray, this would be the complete code:
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int biggestArrayLength = Math.max(arry1.length, arry2.length);
int[] sumArray = new int[biggestArrayLength];
for(int i=0;i<biggestArrayLength;i++){
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
sumArray[i] = result;
System.out.println("Result "+result);
}
}
}
It is because your loop will go from 0 to 6 (which is the array1.length - 1) and your array2 only has 6 elements (so from 0 to 5).
So when you are accessing arry2[6]; It will give you the java.lang.ArrayIndexOutOfBoundsException.
You could change your for loop to go to the length of the smallest array:
for(int i = 0; i < arry2.length; i++){ /*Do what you want */ }
Or add an element in array2, but that is yours to decide since I do not know your requirements.
Because arry1 is longer than arry2 when you make the last iteration through the loop arry2[i] returns null because there is no element to return.
either do:
if(arry2[i] != null) {
//run your adding code
}
or change your arrays to be the same size
Edit: The reason it is not working properly is because you are using the length of the largest array as the conditional within the for loop. This condition allows you to attempt to access the 2nd array at a location that does not exist, which is why you are getting an ArrayIndexOutOfBoundsException.
Can we stop the downvoting?
End edit----
If you want to add up all of the elements in the array use this code.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result+=arry1[i];
}
for(int j=0; j < array2.length; j++){
result += array2[j];
}
System.out.println("Result: "+ result);
}
}
if you are trying to sum individual elements as you loop you can do the following. This will properly handle 2 arrays of different length regardless of which one is longer.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result=arry1[i];
if(i < array2.length){
result += array2[i];
}
System.out.println("Result: "+ result);
}
for(int j = i; j < array2.length; j++){
System.out.println("Result: "+ array2[j]);
}
}
}

Finding elements in array with binary search

Trying to use Arrays.binarySearch() to search for a string in an array and return the index. However each time I call Arrays.binarySearch() I get the following exception -
Exception in thread "main" java.lang.NullPointerException
at java.util.Arrays.binarySearch0(Unknown Source)
at java.util.Arrays.binarySearch(Unknown Source)
at project.ArrayDirectory.lookupNumber(ArrayDirectory.java:97)
at project.test.main(test.java:12)
Here is my ArrayDirectory class -
public class ArrayDirectory implements Directory {
static Entry[] directory = new Entry[50];
#Override
public void addEntry(String surname, String initials, int extension) {
int n = 0;
for (int i = 0; i < directory.length; i++) { // counting number of
// entries in array
if (directory[i] != null) {
n++;
}
}
if (n == directory.length) {
Entry[] temp = new Entry[directory.length * 2]; // if array is full
// double the
// length.
for (int i = 0; i < directory.length; i++)
temp[i] = directory[i];
directory = temp;
}
int position = -1;
for (int i = 0; i < directory.length; i++) {
position = i;
if (directory[i] != null) { // sorting the array into alphabetical
// order by surname.
int y = directory[i].getSurname().compareTo(surname);
if (y > 0) {
break;
}
}
else if (directory[i] == null) {
break;
}
}
System.arraycopy(directory, position, directory, position + 1,
directory.length - position - 1);
directory[position] = new Entry(initials, surname, extension); // placing
// new
// entry
// in
// correct
// position.
}
#Override
public int lookupNumber(String surname, String initials) {
// TODO Auto-generated method stub
Entry lookup = new Entry(surname, initials);
int index = Arrays.binarySearch(directory, lookup);
return index;
}
}
Any ideas how I use binary search to find the correct index?
Thank you for you help.
edit -
I have also overridden comapreToin my Entry class -
public int compareTo(Entry other) {
return this.surname.compareTo(other.getSurname());
}
In your invocation of
int index = Arrays.binarySearch(directory,lookup);
directory seems to contain only null elements. Check that you are initializing elements correctly.
I note two things:
static Entry [] directory = new Entry [1];
First, that code allocates space for one Entry in the array. It doesn't actually instantiate an Entry. That is, directory[0] is null. Secondly, a binary-search on an array with one entry is crazy. There is only one element. It must be directory[0]. Finally, you should sort your array to do a binary search on it.
The basic concept behind a binary search is the recursion of the following steps(Note the search assumes the list or array of elements is sorted in some form and the element exists there.):
Go to the middle element of the array.
check if the searched element is equal to the element at the middle. If it is then return its index.
if not then check if the searched element is 'smaller' or 'larger' than the element in the middle.
if it is smaller then go to step 1 using only the lower/first half of the array instead of the whole.
else go to step 1 using only the upper/last half of the array instead of the whole.
As the array is continuously divided in 2 it will eventually reach the size of 1 giving the result.
Now, suppose you are looking for an integer in an int array. Here is what the code would be like:
public static int binarySearch(int number, int[] array)
{
boolean isHere = false;
Integer index =0;
for(int i=0;i<array.length;i++)
{
if(array[i] == number)
{
isHere = true;
i = array.length;
}
}
if(!isHere)
{
index = -1;
}
else
{
int arrayStart = 0;
int arrayEnd = array.length;
index = binarySearch(number, arrayStart, arrayEnd, array);
}
return index;
}
private static int binarySearch(int number, int start, int end, int[] array)
{
// this formula ensures the index number will be preserved even if
// the array is divided later.
int middle = (start+ end)/ 2;
if(array[middle] == number)
{
return middle;
}
else
{
if(number < array[middle])
{
//searches the first half of the array
return binarySearch(number, start, middle, array);
}
else
{
// searches the last half of the array
return binarySearch(number, middle, end, array);
}
}
}
You can use the compareTo() method instead of <,>, & == operators in your example. The logic should still be the same.

Is there any counterpart of MATLAB function numel in java?

I'm trying to use numel (function available in Matlab) in java.
Are they any implementations of this function available in java?
I am not sure if this is how you want numel to work but here you have few versions:
version1 - for arrays with irregular size like {{1},{2,3}}
this method will iterate over all elements of array counting them.
public static int numel(Object array) {
if (array == null)
return 1;// I will count nulls as elements since new String[10] is
// initialized with nulls
int total = 1;
if (array.getClass().isArray()) {
total = 0;
int length = java.lang.reflect.Array.getLength(array);
for (int index = 0; index < length; index++) {
total += numel(java.lang.reflect.Array.get(array, index));
}
}
return total;
}
version2 - for arrays with regular size like new String[2][3][4]
this method will only use size of first rows of different levels in array to get it size assuming that rows at same level have same size
public static int regularNumel(Object array) {
if (array == null)
return 1;
int total = 1;
if (array.getClass().isArray()) {
int length = java.lang.reflect.Array.getLength(array);
if (length > 0) {
Object row = java.lang.reflect.Array.get(array, 0);
if (row == null || !row.getClass().isArray())
return length;
else //now we know that row is also array
return length * regularNumel(row);
} else
return 0;
}
return total;
}
class main{
public static void main (String[] args){
// numel returns the number of array elements, as does .length in Java.
int[] testArr = {1,2,3,4,5,6,7,8};
System.out.println(testArr.length);
}
}
// Result: 8
I managed to solve this problem.
How I wish the size of an image, I made a small function that solved my problem.
public static int length(BufferedImage bi)
{
int x;
x=bi.getHeight()*bi.getWidth();
return x;
}
The numel function of matlab
n = numel(A) returns the the number of elements, n, in array A.
You Can make yours like
int arraycount(int a[])
{
int counter;
for(int i=0;i<a.length;i++)
{
counter++;
}
return counter;
}

Categories