15 April 2012

Java Exercise 5 :Write a constructor for this class that takes a String argument and stores it. Write a method that prints out the stored String. An "Input is not a String" exception should be thrown if the input is not a string.




Solution:


public class StringException extends Exception{
private String str;
public StringException(String str){
this.str=str;
}
public String toString(){
return "Enter your name correctly";
// exception message here you can type whatever you want
}
}


// Next Class





import java.util.*;
public class UserDefinedException{
public static void main(String[] arg) throws Exception{
String str = getstring();
        Boolean flag= false;
for(int i=0; i<str.length();i++){
if (((str.charAt(i) < 91) && (str.charAt(i) > 64))||(str.charAt(i) < 123) && (str.charAt(i) > 96))
flag=true;
else
           throw new StringException(str);
}
            if(flag == true)
            System.out.println("Your name is " + "  "+ str);

}
static String getstring(){
Scanner input=new Scanner(System.in);
System.out.println("enter your name");
String m =input.next();
return m;
}


}

// Output

Test1:
enter your name
Faizal
Your name is   Faizal


Test2:

enter your name
Faizal12345
Exception in thread "main" Enter your name correctly
at UserDefinedException.main(UserDefinedException.java:11)







2 comments:

akmal niazi khan said...

This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

Love from

Naviya Nair said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Online Training Java EE Online Training Java EE Online Training Java 8 online training Core Java 8 online training

Java Online Training from India Java Online Training from India Core Java Training Online Core Java Training Online Java Training InstitutesJava Training Institutes

Post a Comment

Related Posts with Thumbnails

Popular Posts

 
;