Control keyboard input in Java - java

I have this program to write and have no idea how to control keyboard input:
Write a method to check whether the word entered is valid or not.
Valid word should:
Have at least 10 characters
Start with a letter
Contain a letter in upper case
Contain at least 3 digits
Contain a special character (e.g. #,$.% …etc)
Contain a space

You don't need to validate it on every key stroke, wait till the user has entered the word, then validate. Assuming you are using console input:
System.out.print("Enter something > ");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
//perform validations on inputString, heres the first one:
//regex could be used instead of multiple if statements
if(inputString.length() < 10) {
System.out.println("Validation failed, word was too short");
}
else if ...

You can use this regular expression:
String REGEX = "(^[a-zA-Z](?=.*\\d{3,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%])(?=\\s+).{10,})";
String INPUT = "your password";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(INPUT);
System.out.println("matches(): "+matcher.matches());
^[a-zA-Z] # Start with a letter
(?=.*\\d{3,}) # at least three digits must occur
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.*[##$%]) # a special character must occur at least once
(?=\\s+) # a space must occur at least once
.{10,} # anything, at least ten places though
$ # end-of-string
To use this, read your password (from file,swing elements,...) and call a method, say validate(String pass), inside validate check it against the regex.

Scanner input=new Scanner(System.in);
System.out.print("Enter Number");
//in here "input" is a Scanner name you can use any name for it as OBAMA.
int x=input.nextInt();
//here you can assigne the key board value for "x".
System.out.println(x);
then you can print it.

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");

Regex for java project

How would I do java regex for the following examples each its taken in by scanner as a string and regex can only be set after the scanner has taken in each part so where regex can be set is after the scanner e.g
Scanner scan = new Scanner(System.in);
String veriableName = scan.nextLine();
String studentID = scan.nextLine();
String word = scan.nextLine();
................
//regex can only be set here
String veriableNamePattern = "";
String studentIDPattern="";
String wordPattern="";
.............
if(veriableNamePattern.matches(veriableNamePattern ){
System.out.println(veriableName + " is valid.");
}
else{
System.out.println(studentID + " is valid.");
}
here are the examples I am trying to do:
A variable name composed of some alphabetic character followed by any sequence of letters or numbers.
A student ID number represented by 7 digits that must start with 1 and end with the letter s.
Any four letter word that ends in ‘ed’.
A product code represented by two digits followed by three capital letters.
Find all € values from €100 to €999 at the beginning of a line.
Just.. read through your code, treat it like a term paper, you proofread those too, surely:
You are calling veriableNamePattern.matches(veriableNamePattern) - it won't, of course. You want to match veriableName.
You print studentID + " is valid." in both cases, making it impossible to tell the difference. presumably you want to introduce a not somewhere in that second println lline.
Some examples:
// first letter optionally followed by a letter/number/underscore (\w) group
String variablePattern = "[a-zA-Z]\\w*";
// Sequence of digits starting with 1, followed by 6 digits, ending with 's' or 'S'
String studentIdPattern = "1[0-9]{6,6}s|S";
// Sequence of 2 letters followed by "ed"
String fourEdPattern = "[a-zA-Z]{2,2}ed";

How to use Pattern and Matcher? [duplicate]

This question already has answers here:
Java regular expressions and dollar sign
(5 answers)
Closed 4 years ago.
I have two simple questions about Pattern.
First one is reading the given name(s) and surname. I need to tell whether they contain numbers or punctuation characters. If not, it's a valid name. Whatever I input, the output is
This is not a valid name.
What am I doing wrong?
Scanner input = new Scanner(System.in);
System.out.print("Enter: ");
String name = input.next();
Pattern p = Pattern.compile("[A-Za-z]");
Matcher m = p.matcher(name);
boolean n = m.matches();
if (n == true) {
System.out.println(name);
}
else {
System.out.println("This is not a valid name.");
}
The second question: I read a list of salary amounts that start with a dollar sign $ and followed by a non-negative number, and save the valid salaries into an array. My program can output an array, but it can't distinguish $.
Scanner sc = new Scanner(System.in);
System.out.print("Enter Salary: ");
String salary = sc.nextLine();
Pattern pattern = Pattern.compile("($+)(\\d)");
Matcher matcher = pattern.matcher(salary);
String[] slArray=pattern.split(salary);
System.out.print(Arrays.toString(slArray));
I wouldn't even use a formal matcher for these simple use cases. Java's String#matches() method can just as easily handle this. To check for a valid name using your rules, you could try this:
String name = input.next();
if (name.matches("[A-Za-z]+")) {
System.out.println(name);
}
else {
System.out.println("This is not a valid name.");
}
And to check salary amounts, you could use:
String salary = sc.nextLine();
if (salary.matches("\\$\\d+(?:\\.\\d+)?")) {
System.out.println("Salary is valid.");
}
A note on the second pattern \$\d+(?:\.\d+)?, we need to escape dollar sign, because it is a regex metacharacter. Also, I did not use ^ and $ anchors in any of the two patterns, because String#matches() by default applies the pattern to the entire string.
Edit:
If you have multiple currency amounts in a given line, then split by whitespace to get an array of currency strings:
String input = "$23 $24.50 $25.10";
String[] currencies = input.split("\\s+");
Then, use the above matching logic to check each entry.
Explanation
Your regex pattern is wrong. You are missing the symbol to repeat the pattern.
Currently you have [A-Za-z] which matches only one letter. You can repeat using
* - 0 to infinite repetitions
? - 0 to 1 repetitions
+ - 1 to infinite repetitions
{x, y} - x to y repetitions
So you probably wanted a pattern like [A-Za-z]+. You can use sites like regex101.com to test your regex patterns (it also explains the pattern in detail). See regex101/n6OZGp for an example of your pattern.
Here is a tutorial on the regex repetition symbols.
For the second problem you need to know that $ is a special symbol in regex. It stands for the end of a line. If you want to match the $ symbol instead you need to escape it by adding a backslash:
"\\$\\d+"
Note that you need to add two backslashes because the backslash itself has a special meaning in Java. So you first need to escape the backslash using a backslash so that the string itself contains a backslash:
\$\d+
which then is passed to the regex engine. The same if you want to match a + sign, you need to escape it.
Notes
If you just want to check a given String against a pattern you can use the String#matches method:
String name = "John";
if (name.matches("[A-Za-z]+")) {
// Do something
}
Also note that there are shorthand character classes like \w (word character) which is short for [A-Za-z0-9_].
Code like
if (n == true) { ... }
can be simplified to just
if (n) { ... }
Because n already is a boolean, you don't need to test it against true anymore.
To parse currency values you should consider using already given methods like
NumberFormat format = NumberFormat.getCurrencyInstance();
Number num = format.parse("$5.34");
See the documentation of the class for examples.

what will be the regex that allow only one special character in a string. e.g if a user enter a special character twice (##) then it will show invalid

import java.util.Scanner;
public class fahad
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if (s.matches("\\w{2,}\\.{0,1}\\w{2,}#\\D+\\.com"))
System.out.println("Valid: ");
else
System.out.println("Invalid: ");
}
}
There are at least two possible approaches. The easier one is to use negative lookahead:
if (s.matches("(?!.*##.*$).*")) {
System.out.println("Valid: ");
}
The lookahead assertion matches zero characters, but it matches successfully only if the pattern inside is not matched by whatever part of the input has not been matched by any previous part of the pattern (of which there is none in this case).
It's more instructive (and more widely applicable) to approach it constructively, however:
if (s.matches("[^#]*(#[^#]+)*#?")) {
System.out.println("Valid: ");
}
That matches an initial substring of non-# characters, followed by zero or more appearances of exactly one # followed by one or more non-# characters, optionally ending with one #. It will match any string -- including an empty one -- that does not contain two adjacent # characters.

How do I ensure that the user does not enter numbers in his / her name?

I am asking the user to enter his/her name.
What can I do so that numbers won't be excepted?
String name = " ";
System.out.println("Enter Name");
name = Keyboard.readString();
Use regex to check the input and a loop to get a good answer:
String name = "";
while (true) {
System.out.println("Enter Name");
name = Keyboard.readString();
if (name.matches("[a-zA-Z]+"))
break;
System.out.println("Invalid input. Enter letters only");
}
boolean numberOrNot = name.matches(".*\\d.*");
numberOrNot will be true if it name has any number, else it will be false.
regex means, Regular Expressions.
-?\\d+ is a regex.
-?: negative sign, could have none or one
\\d+: one or more digits
But this is validation, I don't think you can put limitation on console.
You cant make user put only characters in console and nothing else while typing, but you can validate his input and check if it contains only alphabetic characters after he put it and in case of invalid one ask user to type his data again.
To check if String contains only alphabetic characters you can iterate over all its characters and use Character.isAlphabetic(character) on them or just use matches with regex like this one userData.matches("\\p{IsAlphabetic}+");
Character.isAlphabetic and \\p{IsAlphabetic} has advantage over checking a-zA-Z range because it will also accept non English characters like ą, ę.

Categories