Reputation: 81
I want that as soon as my exception is raised it breaks my loop(using break function) & print i(length of array)
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);
}
}
Upvotes: 0
Views: 1729
Reputation: 724
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);
}
}
Upvotes: 0
Reputation: 201439
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
static int length(String p){
if (p == null) return 0;
int count = 0;
for (char ch : p.toCharArray()) {
count++;
}
return count;
}
Upvotes: 0
Reputation: 7194
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);
}
}
Upvotes: 0
Reputation: 35557
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
Upvotes: 3