如何在不使用库的情况下计算数组的长度

How to calculate a length of array with out using library

昨天我去面试了,面试官让我写一个代码来计算数组的长度,而不是使用数组class的长度属性。

例如-

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

给出的所有答案 here 都在使用字符串库。

试试这个:

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

根据我在评论中的建议,这绝对不是一个好的做法。

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

输出:

Enter something: Banana
Length: 6

更好的解决方案可能是使用以下方法:java.lang.reflect.Array::getLength

例如:

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