简体   繁体   中英

How to calculate a length of array with out using library

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.

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));
    }

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM