Question:
How do I code a Java Program to catch an error when a user enters a number into a non numeric field?
red_head_with_attitude123
2009-11-12 00:00:26 UTC
I am creating a program that asks a user to enter their name and birth year and then the program will display this information once the user clicks on the "Show Answer" button. I understand how to code the program to catch the error if the user enters a non-numeric value into the birth year field but how do I code the program to catch the error if the user enters a number into the name field? Thank you.
Four answers:
McNile
2009-11-12 00:08:33 UTC
You could do a pars and make sure that all the letters in the string are are the ascii values from 'A' (ascii 41) through what ever 'z' is in ascii. That is one way you could do it.
rclakmal
2009-11-13 23:32:50 UTC
/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package examples;



import java.util.Scanner;



/**

*

* @author lakmal

*/

public class Name {



String name;



void getName() {

Scanner input = new Scanner(System.in);

System.out.println("Enter Your name:");

name = input.next();

this.checkName();

}



void checkName() {

boolean isValid = true;

for (int i = 0; i < name.length(); i++) {



if (Character.isDigit(name.charAt(i))) {

isValid = false;

continue;

}



}

if (isValid) {

System.out.println("Your name is " + name);



} else {

System.out.println("Name should not have any Integers");

this.getName();

}



}



public static void main(String[] args) {

Name name1 = new Name();

name1.getName();



}

}





check this out !! Hope you will understand the code !!!
brasier
2016-10-17 03:21:18 UTC
with merely 2 contraptions what you ought to do is have a for loop with a nested for loop. Have each and each set of words indexed in a separate array. Index the 1st for loop from 0 - array1.length()-a million, index the 2nd for loop from 0 - array2.length()-a million. Output a string from array1 such as the index of the 1st for loop and output a string from array2 such as the index of the 2nd for loop.
AnalProgrammer
2009-11-12 04:31:27 UTC
Try something like this.



String name = new String("Joe Blogs");

if (name.matches("[a-z|A-Z|\\p{Blank}]*")) {

//Name is valid contains alpha char or space or tab char.

} else {

//Name contains a digit or an non alpha character.

}



I hope this helps.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...