How to calculate a length of array with out using library

136 views Asked by At

yesterday I appeared in interview,interviewer told me to write a code for calculating a length of array with out using a length property of Array class.

For examaple-

char[] array=new Scanner(System.in).nextLine().toCharArray();
// i have to write a code for calculating length of this array
//I can use any operator but use of library is restricted

All answer given here are using String library.

4

There are 4 answers

4
Sestertius On BEST ANSWER
char[] array = new Scanner(System.in).nextLine().toCharArray();
int count = 0;
for (int i : array) {
    count++;
}
System.out.println(count);
0
Diabolus On

try this:

    char []c = {'a', 'b', 'c'};
    int i = 0;
    int l = 0;
    try{
    while(c[i++] != 0)
    {
        System.out.println(c[i-1]);
        l++;
    }
    }catch(Exception a)
    {};
    System.out.println(l);
4
almightyGOSU On

As per my suggestion in the comments, which is definitely not good practice.

import java.util.Scanner;

public class QuickTester {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter something: ");
        char [] charArr = sc.nextLine().toCharArray();

        int i = 0;
        try {
            while(true) {
                char c = charArr[i++];
            }
        }
        catch (ArrayIndexOutOfBoundsException e) {

        }

        System.out.println("Length: " + (i-1));
    }
}

Output:

Enter something: Banana
Length: 6
4
gontard On

A nicer solution might be to use the method: java.lang.reflect.Array::getLength

For example:

import java.lang.reflect.Array;

public class ArrayLength {
    public static void main(String[] args) {
        char[] array = new char[]{'a', 'b', 'a', 'c'};
        System.err.println(Array.getLength(array));
    }

}