对于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
给出here的所有答案都在使用字符串库。
答案 0 :(得分:2)
更好的解决方案可能是使用该方法: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));
}
}
答案 1 :(得分:1)
char[] array = new Scanner(System.in).nextLine().toCharArray();
int count = 0;
for (int i : array) {
count++;
}
System.out.println(count);
答案 2 :(得分:0)
试试这个:
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);
答案 3 :(得分:0)
根据我在评论中提出的建议,这绝对不是一种好的做法。
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