What I am trying to do is put the # character before the domain. Im also trying to figure out how to put the domains to be the last 4 characters (example .com). How do I go about doing this? Any help would be appreciated.
I have listed my work on this link.
Code from the link:
import java.util.Scanner;
public class Username {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Must be between 8 and 20 characters.");
System.out.println("Must contain at least one uppercase and lowercase letter.");
System.out.println("Must contain at least one digit. ");
System.out.println("Must contain a special character ] [ ? / < ~ # ! $ % ^ & * ( ) + = } | : ; , > { ");
System.out.println("Must contain # before the domain");
System.out.println("The only acceptable domains are .com .edu .org .mil .gov .net");
System.out.println("\\n____Please enter your username to access the page. Follow the rules above.____ ");
String input = keyboard.nextLine();
while ((input.length() < 8) || (input.length() > 20))
{
System.out.println("Error! Your input is not valid.");
System.out.println("Please try again.");
keyboard.nextLine();
}
for (int i = 0; i <= input.length(); i++)
{
if(Character.isUpperCase(input.charAt(i)))
{
break;
}
else
{
if(i == input.length())
{
System.out.println("Error: Try again");
input = keyboard.nextLine();
}
}
}
for (int i = 0; i <= input.length(); i++)
{
if(Character.isLowerCase(input.charAt(i)))
{
break;
}
else
{
if(i == input.length())
{
System.out.println("Try again");
input = keyboard.nextLine();
}
}
}
char [] numbers= {\'0\',\'1\',\'2\',\'3\', \'4\',\'5\',\'6\',\'7\',\'8\',\'9\'};
char[] inputArray = input.toCharArray();
for (int i = 0; i < inputArray.length; i++)
{
for (int j = 0; j < numbers.length; j++)
{
if (inputArray[i]== numbers[j])
{
i=inputArray.length;
j=numbers.length;
}
else
{
if(i == inputArray.length-1 && j== numbers.length-1)
{
System.out.println("Try again");
input = keyboard.nextLine();
}
}
}
char [] SpecialCharacter = {\']\',\'[\',\'?\',\'/\',\'<\',\'~\',\'#\',\'.\',\'!\',\'$\',\'%\',\'^\',\'&\',\'*\',\'(\',\')\',\'+\',\'=\',\'}\',\'|\',\'>\',\'{\' };
char[] inputArray2 = input.toCharArray();
for (int k = 0; k < inputArray2.length; k++)
{
for (int l = 0; l < SpecialCharacter.length; l++)
{
if (inputArray2[k]== SpecialCharacter[l])
{
k=inputArray2.length;
l=SpecialCharacter.length;
}
else
{
if(k == inputArray2.length-1 && l == SpecialCharacter.length-1)
{
System.out.println("No...Try Again");
input = keyboard.nextLine();
}
}
}
String domain1 = ".com";
String domain2 = ".edu";
String domain3 = ".org";
String domain4 = ".mil";
String domain5 = ".gov";
String domain6 = ".net";
}
}
}
}
if you only need to verify that the user has entered a valid email or not then you should use regular expersion for that it makes it more easy and fast.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^(?=.*[0-9]*[a-z]*[A-Z])(?=.*[a-zA-Z])([a-zA-Z0-9]{8,20}+#[A-Za-z0-9]+.(com|org|edu|mil|net))$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
*
* #param hex
* hex for validation
* #return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
hope this will help you. =)
i'll just put this here...
Insert the parts of your code where needed.
import java.util.Scanner;
public class Username {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Must be between 8 and 20 characters.");
System.out.println("Must contain at least one uppercase and lowercase letter.");
System.out.println("Must contain at least one digit. ");
System.out.println("Must contain a special character ] [ ? / < ~ # ! $ % ^ & * ( ) + = } | : ; , > { ");
System.out.println("Must contain # before the domain");
System.out.println("The only acceptable domains are .com .edu .org .mil .gov .net");
System.out.println("\\n____Please enter your username to access the page. Follow the rules above.____ ");
boolean isOK = false;
String input=new String();
while(!isOK){
input=keyboard.nextLine();
if(input.length() < 20 || input.length() > 8) //length check
{
isOK=true;
}
else
{
isOK=false;
continue;
}
if(input.contains('#')) //check domain
{
isOK=true;
}
else
{
isOK=false;
System.out.println("No # before domain!");
continue;
}
String[] tokens = input.split("#");
String domain=tokens[1];
String username=tokens[0];
//check if contains digit
...
//check uppercase and lowercase in username
...
//check special character in username
...
//split domain
tokens = domain.split(".");
String domainEnding = tokens[1];
//check if the input domain endings are allowed
...
}
}
}
So where the part of input is wrong just use isOK=false;
continue;
BTW: why are you using \' in special character and number arrays?
You could use just '1' , '#' etc.
Related
I'm making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, "vowels:" multiple times before. I've tried moving the print statement and the braces around but it says "error: 'else if' without 'if'". I'm completely new to Java so sorry if the solution is in plain sight. Thank you in advance :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels= 0;
int l;
l= text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i,i+1);
if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0||
wordPRT.compareToIgnoreCase("i")==0
|| wordPRT.compareToIgnoreCase("o")==0
|| wordPRT.compareToIgnoreCase("u")==0){
vowels++;
System.out.println("vowels: " + vowels);
}
else if(vowels<1){
System.out.print("no vowels");
}
}
}
}
You are printing everything in a for loop instead of count vowels and print at the end.
try something like:
int vowelsCounter = 0;
for(...) {
... logic to count the vowels
if(isvowel(string.charAt(i)){
vowelsCountr++;
}
}
if(vowelsCounter > 0 ) {
printSomething
}
else {
print something else
}
Also You should not use subString for this kind of a loop but string.charAt(i)
Move the print statements out of the for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels = 0;
int l;
l = text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i, i + 1);
if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
|| wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
|| wordPRT.compareToIgnoreCase("u") == 0) {
vowels++;
}
}
if (vowels >= 1) {
System.out.println("vowels: " + vowels);
} else {
System.out.print("no vowels");
}
}
}
A sample run:
Enter text: Hello
vowels: 2
import java.awt.Component;
import javax.swing.JOptionPane;
public class DoSomething {
public static void main(String[] args) {
String password = JOptionPane.showInputDialog(null,
"Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
Component frame = null;
int counter = 0;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
if (password.matches("a-zA-Z")) {
counter++;
character= true;
}
}
if(Character.isLetterOrDigit(c)) {
counter++;
symbol = false;
}
if(Character.isDigit(c)) {
counter++;
if (counter >=2) {
number = true;
}
if (password.length()>=8) {
length = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog("Your Password " +password +" is valid")
}
}
}
Edited -- it still hates length (even if it is 8 or more)
Why not just use regular expressions ?
public static boolean isValid(String password) {
return password.matches("([a-zA-Z]{8,})([0-9]{2,})");
}
This expression (if I'm not mistaken) checks if there are 8 or more characters(lowercase and uppercase) and if there are more than two numbers in the password. Symbols such as $, #, [space] will trigger the expression as false. EDIT: This regular expression only allows a password with 8 (or more) grouped characters and 2 (or more) numbers. Numbers cannot be separated (1MyPassword3) as this will flag the password as invalid. Further investigation will be required.
See the java API for regular expressions:
java 7 Pattern class
java 8 Pattern class
Also check out String.matches(String regex)
Reaction on comment
This code should suit you better then:
int letterCount = 0;
int numberCount = 0;
/*
* Loop through the password and count all the letters and characters
*/
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.toString(c).matches("[a-zA-Z]")) {
letterCount++;
}
if (Character.toString(c).matches("[0-9]")) {
numberCount++;
}
}
if (letterCount > 8) {
// password has 8 or more characters
}
if (numberCount > 2) {
// password has more than 2 numbers
}
Then if you really want to check length as well, you can add this piece of code (outside the for-loop)
if (password.length() >= 10) {
/* Since we need 2 numbers and 8 characters, the password
* can never be valid if it's smaller than 10 characters
*/
else {
/*
* Invalid password
*/
}
Assuming that your conditions for a valid password were:
At least 8 letters
At least 2 numbers
No symbols
At least 10 characters long
String password = JOptionPane.showInputDialog(null, "Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
int letterCounter = 0;
int numCounter = 0;
Component frame = null;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
letterCounter++;
}
else if(Character.isDigit(c)) {
numCounter++;
}
else {
symbol = true;
}
}
//Checking booleans
if (password.length()>=10) {
length = true;
}
if (letterCounter>=8) {
character = true;
}
if (numCounter>=2) {
number = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog(frame, "Your Password " + password + " is valid");
System.out.println("Success");
}
else {
System.out.println("Invalid");
}
I am trying to find if a phone number fits the format (xxx)xxx-xxxx where x is a digit. First, I have the program for the length and the '(',')', and '-'. When I type in something that doesn't work, I get the logical output. However, when I type in a properly formatted number, my program doesn't return anything.
import java.util.Scanner;
public class Program04 {
public static void main(String args[])
{
Scanner stdIn = new Scanner(System.in);
String pN;
System.out.print("Please enter a phone number (ddd)ddd-dddd :");
pN = stdIn.nextLine();
char a = pN.charAt(1);
char b = pN.charAt(2);
char c = pN.charAt(3);
char d = pN.charAt(5);
char e = pN.charAt(6);
char f = pN.charAt(7);
char g = pN.charAt(9);
char h = pN.charAt(10);
char i = pN.charAt(11);
char j = pN.charAt(12);
if (pN.length() == 13 && pN.charAt(0)=='(' && pN.charAt(4)== ')' && pN.charAt(8)=='-')
{
if (a>=0 && a<=9)
{
if (b>=0 && b<=9)
{
if (c>=0 && c<=9)
{
if (d>=0 && d<=9)
{
if (e>=0 && e<=9)
{
if (f>=0 && f<=9)
{
if (g>=0 && g<=9)
{
if (h>=0 && h<=9)
{
if (i>=0 && i<=9)
{
if (j>=0 && j<=9)
{
System.out.print("This is a valid phone number!");
}
}
}
}
}
}
}
}
}
}
}
else System.out.println("Not a vaid phone number.");
}
}
It's easier to use pattern-matching (regex) for validation:
...
pN = stdIn.nextLine();
System.out.println(pN.matches("\\(\\d{3}\\)\\d{3}-\\d{4}"));
Even if you want to have it check if each character is a digit, using so many nested if's is not the way to go. Instead, define a simple method that applies the check, say:
private static boolean isDigit(char x) {
return x>=0 && x<=9;
}
and then do:
if ( isDigit(a) && isDigit(b) && ...) {
return true;
}
else {
return false;
}
If you're not allowed to use RegEx or if it is too difficult to understand, try simplifying your nested if's by a simple switch inside a loop, it is much more readable and maintenance is the easiest :
public static void main(String[] args) {
String pn = scan.nextLine();
boolean valid = true;
if (pn.length() == 13){
for (int i = 0 ; i < 13 ; i++){
switch(i){
case 0 : valid = pn.charAt(0) == '(';break;
case 4 : valid = pn.charAt(4) == ')';break;
case 8 : valid = pn.charAt(8) == '-';break;
default : valid = Character.getNumericValue(pn.charAt(i)) >= 0 && Character.getNumericValue(pn.charAt(i))<= 9 ; break;
}
if (!valid) break;
}
if (!valid) System.out.println("Invalid number");
}else{
valid = false;
System.out.println("Invalid length");
}
if (valid){
System.out.println(pn + " is a valid telephone number");
}
}
Also, to avoid working with the ASCII value of a char, try using the Character.getNumericValue(Char c) method. It returns a numeric that you can use for your tests, like above.
It is better to use regex in this case:
You can use following :
String pattern = "(\\(\\d{3}\\)\\d{3}-\\d{4})";
Pattern r = Pattern.compile(pattern);
pN = stdIn.nextLine();
Matcher m = r.matcher(pN);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
Problem Description:
Some Websites impose certain rules for passwords. Write a method that checks whether a string is a valid password. Suppose the password rule is as follows:
A password must have at least eight characters.
A password consists of only letters and digits.
A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays "valid password" if the rule is followed or "invalid password" otherwise.
This is what I have so far:
import java.util.*;
import java.lang.String;
import java.lang.Character;
/**
* #author CD
* 12/2/2012
* This class will check your password to make sure it fits the minimum set requirements.
*/
public class CheckingPassword {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
//return true if and only if password:
//1. have at least eight characters.
//2. consists of only letters and digits.
//3. must contain at least two digits.
if (password.length() < 8) {
return false;
} else {
char c;
int count = 1;
for (int i = 0; i < password.length() - 1; i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
count++;
if (count < 2) {
return false;
}
}
}
}
return true;
}
}
When I run the program it only checks for the length of the password, I cannot figure out how to make sure it is checking for both letters and digits, and to have at least two digits in the password.
Suppose a valid password has:
8 or more characters, but not more than 16 characters
one or more uppercase characters
one or more lowercase characters
one or more digits
one or more special characters (like $, #, or !)
Code:
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
// TODO Auto-generated method stub
int min =8;
int max=16;
int digit=0;
int special=0;
int upCount=0;
int loCount=0;
String password;
Scanner scan = new Scanner(System.in);
System.out.println(" Enter Your Password:");
password = scan.nextLine();
if(password.length()>=min&&password.length()<=max){
for(int i =0;i<password.length();i++){
char c = password.charAt(i);
if(Character.isUpperCase(c)){
upCount++;
}
if(Character.isLowerCase(c)){
loCount++;
}
if(Character.isDigit(c)){
digit++;
}
if(c>=33&&c<=46||c==64){
special++;
}
}
if(special>=1&&loCount>=1&&upCount>=1&&digit>=1){
System.out.println(" Password is good:");
}
}
if(password.length()<min){
for(int i =0;i<password.length();i++){
char c = password.charAt(i);
if(Character.isLowerCase(c)){
loCount++;
}
}
if(loCount>0){
System.out.println(" Password must be atleat "+min+" characters:");
System.out.println(" You need atleast one upper case chracter:");
System.out.println(" You need atleast one digit:");
System.out.println(" You need atleast one special chracter:");
}
}
else if(password.length()<min&&upCount>1){
for(int i =0;i<password.length();i++){
char c =password.charAt(i);
if(Character.isLowerCase(c)){
loCount++;
}
if(Character.isUpperCase(c)){
upCount++;
}
}
if(loCount>0&&upCount>0){
System.out.println(" Password must be atleast "+min+" chracters:");
System.out.println(" You need atleast one digit:");
System.out.println(" You need atleast one special chracter:");
}
}
if(password.length()>max||password.length()>=max&&upCount>1&&loCount>1&&digit>1){
System.out.println(" Password is too long.Limit is "+max+" chracters:");
System.out.println(" You need atleast one special chracter:");
}
if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit>0&&special==0){
System.out.println(" You need atleast a special chracter");
}
if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit==0&&special==0){
System.out.println(" You need atleast one digit:");
System.out.println(" You need atleast one special chracter:");
}
}
}
You almost got it. There are some errors though:
you're not iterating over all the chars of the password (i < password.length() - 1 is wrong)
you start with a digit count of 1 instead of 0
you make the check that the count of digits is at least 2 as soon as you meet the first digit, instead of checking it after you have scanned all the characters
As previously answered, you should chek all the password characters first. Count your digits and finally check if count is smaller than 2.
Here is the referring code.
if (password.length() < 8) {
return false;
} else {
char c;
int count = 0;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
count++;
}
}
if (count < 2) {
return false;
}
}
return true;
}
public void run()
{
String password= readLine("Insert Password: ");
boolean len= true;
boolean letter= true;
boolean twodig= true;
if (password.length() < 8) {
len = false;
} else {
char c;
int count = 0;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
letter = false;
} else if (Character.isDigit(c)) {
count++;
}
}
if (count < 2) {
twodig = false;
}
}
if(len ==true && letter == true && twodig == true)
{
System.out.println("This password is valid ");
}
else
{
System.out.println("This password is invalid");
}
}
package Method;
/*
2. Write a Java method to check whether a string is a valid
password.
Password rules:
A password must have at least ten characters.
A password consists of only letters and digits.
A password must contain at least two digits.
Expected Output:
A password must have at least eight characters.
A password consists of only letters and digits.
A password must contain at least two digits
Input a password (You are agreeing to the above Terms and Conditions.): abcd1234
Password is valid: abcd1234
*/
public class CheckPassword {
public static String password;
public static int disitCounter = 0;
public static boolean isValid(String password) {
if (password.length() >= 10 ) {
for(int index = 0; index < password.length(); index++) {
char passChar = password.charAt(index);
if (!Character.isLetterOrDigit(passChar)) {
return false;
}
else {
if (Character.isDigit(passChar)) {
disitCounter++;
}
}
}
}
if(disitCounter < 2) {
return false;
}
return true;
}
public static void main(String[] args) {
password = "abcdefgh1w3";
if(isValid(password)) {
System.out.print("It is a valid password");
}
else {
System.out.print("It is a invalid password");
}
}
}
package com.parag;
/*
* #author Parag Satav
*/
public boolean check(String password) {
boolean flagUppercase = false;
boolean flagLowercase = false;
boolean flagDigit = false;
boolean flag = false;
if (password.length() >= 10) {
for (int i = 0; i < password.length(); i++) {
if (!Character.isLetterOrDigit(password.charAt(i))) {
return false;
}
if (Character.isDigit(password.charAt(i)) && !flagDigit) {
flagDigit = true;
}
if (Character.isUpperCase(password.charAt(i)) && !flagUppercase) {
flagUppercase = true;
}
if (Character.isLowerCase(password.charAt(i)) && !flagLowercase) {
flagLowercase = true;
}
}
}
if (flagDigit && flagUppercase && flagLowercase) {
flag = true;
System.out.println("Success..");
} else
System.out.println("Fail..");
return flag;
}
I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.