java Exceptions Enter String only - java

How to catch integer if the user must input String only, no integer and Symbols included to the input? Help me sir for my beginner's report.
import java.util.*;
public class NameOfStudent {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name = "";
System.out.print("Please enter your name: ");
name = input.nextLine(); // How to express error if the Strin contains
//integer or Symbol?...
name = name.toLowerCase();
switch(name)
{
case "cj": System.out.print("Hi CJ!");
break;
case "maria": System.out.print("Hi Maria!");
break;
}
}
}

Use this regular expression.
Check if a String contains number/symbols etc..
boolean result = false;
Pattern pattern = Pattern.compile("^[a-zA-Z]+$");
Matcher matcher = pattern.matcher("fgdfgfGHGHKJ68"); // Your String should come here
if(matcher.find())
result = true;// There is only Alphabets in your input string
else{
result = false;// your string Contains some number/special char etc..
}
Throwing custom exceptions
Throwing custom exceptions in java
Working of a try-catch
try{
if(!matcher.find()){ // If string contains any number/symbols etc...
throw new Exception("Not a perfect String");
}
//This will not be executed if exception occurs
System.out.println("This will not be executed if exception occurs");
}catch(Exception e){
System.out.println(e.toString());
}
I just given a overview, how try-catch works. But you should not use a general "Exception" ever. always use your customized exception for your own exceptions.

Once you have the String in your hand, e.g. name you can apply a regexp to it as follows.
String name = "your string";
if(name .matches(".*\\d.*")){
System.out.println("'"+name +"' contains digit");
} else{
System.out.println("'"+name +"' does not contain a digit");
}
Adapt the logic checks to your needs.

Please be aware that a string can contain numeric character, and it's still a string:
String str = "123";
I think what you meant in your question is "How to enforce alphabetical user input, no numeric or symbol", which can be easily done using regular expression
Pattern pattern = Pattern.compile("^[a-zA-Z]+$"); // will not match empty string
Matcher matcher = pattern.matcher(str);
bool isAlphabetOnly = matcher.find();

Use Regex which is a sequence of characters that forms a search pattern:
Pattern pattern = Pattern.compile("^[a-zA-Z]*$");
Matcher matcher = pattern.matcher("ABCD");
System.out.println("Input String matches regex - "+matcher.find());
Explanation:
^ start of string
A-Z Anything from 'A' to 'Z', meaning A, B, C, ... Z
a-z Anything from 'a' to 'z', meaning a, b, c, ... z
* matches zero or more occurrences of the character in a row
$ end of string
If you also want to check for empty string then replace * with +
If you want to do it without regex then:
public boolean isAlpha(String name)
{
char[] chars = name.toCharArray();
for (char c : chars)
{
if(!Character.isLetter(c))
{
return false;
}
}
return true;
}

You can change your code as follows.
Scanner input=new Scanner(System.in);
System.out.print("Please enter your name: ");
String name = input.nextLine();
Pattern p=Pattern.compile("^[a-zA-Z]*$");// This will consider your
input String or not
Matcher m=p.matcher(name);
if(m.find()){
// your implementation for String.
} else {
System.out.println("Name should not contains numbers or symbols ");
}
Follow this link more about Regex. And test some regex by your self from here.

In Java you formulate what the String is allowed to contain in a regular expression. Then you check if the String contains the allowed sequence - and only the allowed sequence.
Your code looks like this. I've added a do-while-loop to it:
Scanner input = new Scanner(System.in);
String name = "";
do { // get input and check for correctness. If not correct, retry
System.out.print("Please enter your name: ");
name = input.nextLine(); // How to express error if the String contains
//integer or Symbol?...
name = name.toLowerCase();
} while(!name.matches("^[a-z][a-z ]*[a-z]?$"));
// The above regexp allows only non-empty a-z and space, e.g. "anna maria"
// It does not allow extra chars at beginning or end and must begin and end with a-z
switch(name)
{
case "cj": System.out.print("Hi CJ!");
break;
case "maria": System.out.print("Hi Maria!");
break;
}
Now you can change the regular expression, e.g. to allow names with asian character sets. Take a look here how to handle predefined character sets. I was once checking any text for words in any language (and any part of the UTF-8 character set) and ended up with a regular expression like this to find the words in a text: "(\\p{L}|\\p{M})+"

if we want to check that two different user enter same email id while registration.....
public User updateUsereMail(UserDTO updateUser) throws IllegalArgumentException {
System.out.println(updateUser.getId());
User existedUser = userRepository.findOneById(updateUser.getId());
Optional<User> user = userRepository.findOneByEmail(updateUser.getEmail());
if (!user.isPresent()) {
existedUser.setEmail(updateUser.getEmail());
userRepository.save(existedUser);
} else {
throw EmailException("Already exists");
}
return existedUser;
}

Scanner s = new Scanner(System.in);
String name;
System.out.println("enter your name => ");
name = s.next();
try{
if(!name.matches("^[a-zA-Z]+$")){
throw new Exception("is wrong input!");
}else{
System.out.println("perfect!");
}
}catch(Exception e){
System.out.println(e.toString());
}

umm..try storing the values in an array..for each single value , use isLetter() and isDigit() ..then construct a new string with that array
use try catch here and see !
i am not used to Pattern class ,use that if thats' simpler

Related

How to I validate the characters in a string in a specific order?

So I'm supposed to use the scanner to read the users employee number and then put that into a method that returns a boolean value. The employee is supposed to have the form DDDDD-LDDDD with the d being digits and l being letters. If the input matches this format I'm supposed to inform the user that they have a valid number and if it doesn't then I have to say it's invalid. I've trying to separate into two substrings to be able to see if they contain digits as well as to see if it contains a letter. I then try to combine these using a loop and if it's in that format the user is told it's valid and if it's not they are informed it's not. Is there any other possible way to check and see if the employee number is composed of digits besides obviously the dash and letter that I can then use to prompt the user if what they wrote is valid? This is only written in Java
You can use regular expressions:
final String[] strings = {
"54321-A1234", // A valid employee ID
"012948B9832", // The dash is replaced with a number
"39832-30423", // The letter is replaced with a number
"24155-C90320", // A valid employee ID but the last number
};
for (String string : strings) {
if (string.matches("[0-9]{5}-[A-Za-z]{1}[0-9]{4}")) {
System.out.println("The string " + string + " is a valid pattern.");
} else {
System.out.println("The string " + string + " is an invalid pattern.");
}
}
This will output
The string 54321-A1234 is a valid pattern.
The string 012948B9832 is an invalid pattern.
The string 39832-30423 is an invalid pattern.
The string 24155-C90320 is an invalid pattern.
Explanation:
[0-9]{5} means "match exactly five digits";
- means "match the character - exactly one time";
[A-Za-z]{1} means "match exactly one letter, case-insensitive";
[0-9]{4} means "match exactly four digits";
Note that [0-9] can be replaced with \\d and that {1} is optional, but I've added just for explicitness.
You can do it with a regular expression. This prompts for the string and if not in proper format, reprompts.
Scanner input = new Scanner(System.in);
String str = null;
System.out.println("Please enter string in DDDDD-LDDDD format");
while (true) {
str = input.nextLine();
// checks for 5 digits followed by - one letter and four digits.
if(str.matches("\\d{5}-\\p{Alpha}\\d{4}")) {
break;
}
System.out.println("Please try again!");
}
System.out.println(str + " is a valid string");

How to check for integer string

I'm supposed to write a program that takes in a string representing an integer as input, and outputs yes if every character is a digit 0-9.
I have gone back through my chapters reading and gone through Google, but I'm still having trouble. I know my code is a mess but I am lost. I may have bits and pieces correct or be wrong all together but this is what I have.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userString;
// Add more variables as needed
userString = scnr.next();
boolean check1 = Character.isDigit(userString);
while (check1 = True) {
System.out.println ("Yes");
}
System.out.println ("No");
Where did I go wrong?
As pointed out by people in comments, there are some mistakes in your code. Character.isDigit won't work with String. What you need to use is Integer.parseInt(...). You can put it in a try catch block; Print yes if parsing is successful and print No if exception is thrown:
userString = scnr.next();
try {
int parsedValue = Integer.parseInt(userString);
// Do something with parsedValue
System.out.println("Yes");
} catch (NumberFormatException numberFormatException) {
System.out.println("No");
}
You could use regular expressions for that:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// your input, can also be from a scanner
String input = "1234567890";
// regex pattern to match a string that consists only of numbers and is also not empty
String regex = "^[0-9]+$";
// to match negative numbers as well: "^[\\-]?[0-9]+$"
// create a pattern object
Pattern pattern = Pattern.compile(regex);
// create a matcher object
Matcher matcher = pattern.matcher(input);
// check if the input matches
if (matcher.find()) {
System.out.println("It's a number, yay!");
};
How does the regex work:
^ matches the beginning of the input to make sure there is nothing before the number characters
[0-9]+ tells it to match the range 0-9 one or more times (+), which also makes sure that an empty string does not match
$ matches the end of the string to make sure there is no non-numbers after the match
If you want to match negative numbers as well, there is an additional part of the regex: [\\-]? this matches one minus sign if there is on or none if there is no sign (?)
https://www.tutorialspoint.com/java/java_regular_expressions.htm
It's also possible the way you tried it:
// open a scanner
Scanner scanner = new Scanner(System.in);
// read user input from the scanner
String input = scanner.next();
// assume it is a number until we find a non-digit character below
String isNumber = true;
// loop over each character of the user input
for (char character : input) {
// check if the character is not a digit
if (!Character.isDigit(character)) {
System.out.println("NOT a number: ", character);
// set the is number variable to false
isNumber = false;
// break the loop, because it cannot be a number because we already found a non-digit
break;
};
};
System.out.println("Is it a number? ", isNumber);

Reject String If Contains Any Non-Alpha Numeric Character

I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.
I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.
My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.
Sample problematic output:
Please enter a search pattern: /
Line number 1
this.a 2test/austin
^
Line number 8
ra charity Charityis 4 times a day/a.a-A
^
Here is my applicable code:
while (again) {
boolean found = false;
System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
String wordToSearch = input.next();
if (wordToSearch.equals("EINPUT")) {
System.out.printf("%s", "Bye!");
System.exit(0);
}
Pattern p = Pattern.compile("\\W*");
Matcher m = p.matcher(wordToSearch);
if (m.find())
found = true;
String data;
int lineCount = 1;
if (found = true) {
try (FileInputStream fis =
new FileInputStream(this.inputPath.getPath())) {
File file1 = this.inputPath;
byte[] buffer2 = new byte[fis.available()];
fis.read(buffer2);
data = new String(buffer2);
Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
while (in.hasNextLine()) {
String line = in.nextLine();
Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println("Line number " + lineCount);
String stringToFile = f.findWords(line, wordToSearch);
System.out.println();
}
lineCount++;
}
}
}
}
Stop reinventing the wheel.
Read this: Apache StringUtils,
Focus on isAlpha,
isAlphanumeric,
and isAlphanumericSpace
One of those is likely to provide the functionality you want.
Create a separate method to call the String you are searching through:
public boolean isAlphanumeric(String str)
{
char[] charArray = str.toCharArray();
for(char c:charArray)
{
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
Then, add the following if statement to the above code prior to the second try statement.
if (isAlphanumeric(wordToSearch) == true)
Well since no one posted REGEX one, here you go:
package com.company;
public class Main {
public static void main(String[] args) {
String x = "ABCDEF123456";
String y = "ABC$DEF123456";
isValid(x);
isValid(y);
}
public static void isValid(String s){
if (s.matches("[A-Za-z0-9]*"))
System.out.println("String doesn't contain non alphanumeric characters !");
else
System.out.println("Invalid characters in string !");
}
}
Right now, what's happening is if the search pattern contains non alphanumeric characters, then do the loop. This is because found = true when the non alphanumeric characters are detected.
if(m.find())
found = true;
What it should be:
if(!m.find())
found = true;
It should be checking for the absence of nonalphanumeric characters.
Also, the boolean flag can just be simplified to:
boolean found = !m.find();
You don't need to use the if statement.

Regular Expression for First Name and Last Name in a single field

I have a scenario where user has to enter its first Name and last name in a single field, so there must be a space between 2 names, and after space there must be atleast a character. I tried to using contains(""), but this method returns true if user just enter a space and does not enter anything after that space.
Kindly guide me a way to achieve this. I have also tried to search Regular Expression but failed to find any.
Here is the regex and a test:
#Test
public void test_firstAndLastName_success() {
Pattern ptrn = Pattern.compile("(\\w+)\\s+(\\w+)");
Matcher matcher = ptrn.matcher("FirstName LastName");
if (matcher.find()) {
Assert.assertEquals("FirstName", matcher.group(1));
Assert.assertEquals("LastName", matcher.group(2));
} else {
Assert.fail();
}
}
The validation is the matcher returning false on find.
If you do not want to permit multiple spaces (\s+) then either remove + (which will still permit for a single tab) or replace it with a space.
You can use code like this:
public static void main(String[] args) throws IOException {
String input = "first last";
if (input.matches("[a-zA-Z]*[\\s]{1}[a-zA-Z].*")) {
String[] name = input.split(" ");
System.out.println(Arrays.toString(name));
} else {
System.out.println("Please input the valid name.");
}
}
It will put first name and last name to array if:
[a-zA-Z]* - input begins with characters;
[\\s]{1} - contains only one space;
[a-zA-Z].* - ends with at least one character.
A simple split using " " will do after trimming the string.
Please check the below code for more understanding :
String[] splitter = null;
String s = "abbsd sdsdf"; // string with 2 words and space
splitter = s.trim().split(" ");
if(splitter.length!=2){
System.out.println("Please enter first or last name");
}
else{
System.out.println("First Name : "+splitter[0]);
System.out.println("Last Name : "+splitter[1]);
}
s = "abc"; //string without space
splitter = s.trim().split(" ");
if(splitter.length!=2){
System.out.println("Please enter first or last name");
}
else{
System.out.println("First Name : "+splitter[0]);
System.out.println("Last Name : "+splitter[1]);
}
Please check with other scenarios with and without space. This should be helpful.

Getting a name as an input using regex in java

I am a beginner in both, Java and regular expressions. I want to get a name as an input, by which I mean that only names that have English alphabets A-Z, case insensitive and spaces.
I am using a Scanner class to get my input but my code doesn't work. It looks like:
Scanner sc= new Scanner(System.in);
String n;
while(!sc.hasNext("^[a-zA-Z ]*$"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
I checked my regular expression on the website regex101.com and found out that it works fine.
For example, If I input it my name, Akshay Arora , the regex site says it is okay but my program prints
That's not a name
That's not a name
Same line is printed twice and it again asks me for input. Where am I going wrong?
Two parts are wrong:
$ and ^ anchors are considered in the context of entire input, not in the context of the next token. It will never match, unless the input has a single line that matches the pattern in its entirety.
You use default delimiters, which include spaces; therefore, Scanner will never return a token with a space in it.
Here is how you can fix this:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
String n;
while(!sc.hasNext("[a-zA-Z ]+"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
Demo.
Here its sample program related to regex.
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputName = sc.next();
String regex = "^[a-zA-Z ]*$";
// Compile this pattern.
Pattern pattern = Pattern.compile(regex);
// See if this String matches.
Matcher m = pattern.matcher(inputName);
if (m.matches()) {
System.out.println("Valid Name");
} else
System.out.println("Invalid Name");
}
}
Hope this will help you

Categories