[英]Calculate the length of an array without using the length property
I want that as soon as my exception is raised it breaks my loop(using break function) & print i(length of array) 我希望在异常出现后立即中断我的循环(使用break函数)并打印i(数组的长度)
class Length{
static void length(String p){
int i=0;
try{
while(i<=i){
char ch=p.charAt(i);
i++;
System.out.println(ch);
}
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String s[]){
String a=new String("jack");
length(a);
}
}
You can change your code as follows 您可以按以下方式更改代码
static int length(String p) {
int i = 0;
try {
while (i <= i) {
char ch = p.charAt(i);
i++;
}
} catch (StringIndexOutOfBoundsException e) { // catch specific exception
// exception caught here
}
return i; // now i is the length
}
public static void main(String s[]) {
String a = "jack";
System.out.println(length(a));
}
Out put: 输出:
4
class Length{
static void length(String p){
int i=0;
try{
while(i<=i){
char ch=p.charAt(i);
i++;
System.out.println(ch);
}
}
catch(Exception e){
System.out.println("String length is : + " i)
// System.out.println(e);
}
}
public static void main(String s[]){
String a=new String("jack");
length(a);
}
}
I think you need to return the length()
you calculate, and you could use the for-each operator on the String
by iterating the char
(s) from toCharArray()
with something like 我认为您需要返回您计算出的
length()
,并且可以使用类似以下内容的迭代toCharArray()
的char
来对String
使用for-each运算符
static int length(String p){
if (p == null) return 0;
int count = 0;
for (char ch : p.toCharArray()) {
count++;
}
return count;
}
Try following application to find out the length of a word 尝试下面的应用程序找出一个单词的长度
public class Length {
public static void main(String[] args) {
new Length().length("Jack");
}
private void length(String word){
int i = 0;
char []arr = word.toCharArray();
for(char c : arr){
i++;
}
System.out.println("Length of the "+ word+ " is "+ i);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.