Regular Expression in Java: Validating user input - java

I am trying to validate user input using a regular expression in a while loop. I am trying to accept only one lower-case word (letters a-z inclusive).
public class testRedex{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Please enter a key: ");
while(!console.hasNext("[a-z]+")){
System.out.println("Invalid key");
console.next();
}
String test = console.next();
System.out.println(test);
}
}
My question is, is there any difference between having the regular expression as "[a-z]+" and "[a-z]+$"? I know that $ will look for a character between a-z at the end of the string, but in this case would it matter?

Yes there is a difference, if you'll use: ^[a-z]+$ it means that whatever the user inputs should be combined only from [a-z]+.
If you don't add the ^ and the $ the user could insert other characters, space for example, and there will still be a match (the first part of the string until the space.
Let's see an example:
run your code with the input: "try this" (it'll print "try")
now change the regex to ^[a-z]+$ and run with the same input (it'll print "Invalid key").
The way I would re-write it is:
System.out.print("Please enter a key: ");
String test = console.nextLine();
while (!test.matches("^[a-z]+$")) {
System.out.println("Invalid key");
test = console.nextLine();
}
System.out.println(test);

The difference are as follows
[a-z]+ means a,b,c,...,or z occurs more than one time
[a-z]+$ means a,b,c,...,or z occurs more that one time and must match end of the line
Yet at the end, they give you the same result.
if you want to understand it better try this
([A-Z])([a-z]+$)
It start with a capital letter and end with more than one time small letter
output:
Please enter a key: AAAAaaaa
Invalid key
Aaaaaa
Aaaaaa
Another way you can get the expected result from what you are looking for
code:
int i = 0;
String result = "";
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter your key:");
if(input.hasNext("^[a-z]+$")){
result = input.next();
i=1;
}else{
System.out.println("Invalid key");
}
}while(i==0);
System.out.println("the result is " + result);
output:
Enter your key:
HHHh
Invalid key
Enter your key:
Hellllo
Invalid key
Enter your key:
hello
the result is hello

Related

How can I obtain the first character of a string that is given by a user input in java

I want the user to input a String, lets say his or her name. The name can be Jessica or Steve. I want the program to recognize the string but only output the first three letters. It can really be any number of letters I decide I want to output (in this case 3), and yes, I have tried
charAt();
However, I do not want to hard code a string in the program, I want a user input. So it throws me an error. The code below is what I have.
public static void main(String args[]){
Scanner Name = new Scanner(System.in);
System.out.print("Insert Name here ");
System.out.print(Name.nextLine());
System.out.println();
for(int i=0; i<=2; i++){
System.out.println(Name.next(i));
}
}
the error occurs at
System.out.println(Name.next(i)); it underlines the .next area and it gives me an error that states,
"The Method next(String) in the type Scanner is not applicable for arguments (int)"
Now I know my output is supposed to be a of a string type for every iteration it should be a int, such that 0 is the first index of the string 1 should be the second and 2 should be the third index, but its a char creating a string and I get confused.
System.out.println("Enter string");
Scanner name = new Scanner(System.in);
String str= name.next();
System.out.println("Enter number of chars to be displayed");
Scanner chars = new Scanner(System.in);
int a = chars.nextInt();
System.out.println(str.substring(0, Math.min(str.length(), a)));
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.
Instead, use code point integer numbers to work with individual characters.
Call String#codePoints to get an IntStream of the code point for each character.
Truncate the stream by calling limit while passing the number of characters you want.
Build a new String with resulting text by passing references to methods found on the StringBuilder class.
int limit = 3 ; // How many characters to pull from each name.
String output =
"Jessica"
.codePoints()
.limit( limit )
.collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
)
.toString()
;
Jes
When you take entry from a User it's always a good idea to validate the input to ensure it will meet the rules of your code so as not to initiate Exceptions (errors). If the entry by the User is found to be invalid then provide the opportunity for the User to enter a correct response, for example:
Scanner userInput = new Scanner(System.in);
String name = "";
// Prompt loop....
while (name.isEmpty()) {
System.out.print("Please enter Name here: --> ");
/* Get the name entry from User and trim the entry
of any possible leading or triling whitespaces. */
name = userInput.nextLine().trim();
/* Validate Entry...
If the entry is blank, just one or more whitespaces,
or is less than 3 characters in length then inform
the User of an invalid entry an to try again. */
if (name.isEmpty() || name.length() < 3) {
System.out.println("Invalid Entry (" + name + ")!\n"
+ "Name must be at least 3 characters in length!\n"
+ "Try Again...\n");
name = "";
}
}
/* If we get to this point then the entry meets our
validation rules. Now we get the first three
characters from the input name and display it. */
String shortName = name.substring(0, 3);
System.out.println();
System.out.println("Name supplied: --> " + name);
System.out.println("Short Name: --> " + shortName);
As you can see in the code above the String#substring() method is used to get the first three characters of the string (name) entered by the User.

How to find an invalid character or symbol inside a string

I'm creating a program that prints user details, first the user inputs their details and then the program correctly formats the details and prints them inside a formatted box. I want the program to read strings and see if the users have entered invalid characters. For example the code below requests for the users first name:
// this code below is used to find the largest string in my program, ignore if this wont interfere
String fname = scan.nextLine(); //main scan point.
//below is used to calculate largest string inputted by the user.
int input = 0;
int fnamelength1 = fname.length();
input = fnamelength1;
int longest = 0;
if(input > longest)
longest = input;
If at this point the user enters #~~NAME~~# as their name, the program currently allows that... I want to make the program read what the user has inputted and print a message if their input isn't correct for example contains invalid symbols.
EDIT:
I'm considering anything other than characters in the alphabet as invalid... any numbers or symbols would therefore be invalid.
VALID:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Also valid:
' - .
This can be done using regular expressions with the String.matches method. Here you define a pattern and if the string matches your pattern then it can be considered valid:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = fname.matches("[^a-zA-Z'-]]");
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
EDIT
With String.matches we can't make a global search of invalid characters (what we want in this case). So is better using Matcher.find for this:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
Pattern pattern = Pattern.compile("[^a-zA-Z'\\-\\s]");
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = pattern.matcher(fname).find();
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
This time the pattern will validate any invalid character anywhere in the string.
One approach would be to use regular expressions, along with the String.matches() method.
As an example:
String fname;
... some code to get fname ...
boolean valid = fname.matches("[a-zA-Z]+");
valid should be true if and only if fname is a String containing alphabetic characters, and not empty.
If empty strings are also valid, then:
boolean valid = fname.matches("[a-zA-Z]*");
Look up the Java class Pattern for other variations.

How to check if a double value contains special characters

I was writing a code for a program in which the user enters 2 to 4 numbers which can be up to 2 decimal places long. However before the user enters these numbers they must enter the pound symbol, e.g. #12.34. I was wondering how i would check if the double value entered began with the pound sign, and if the user forgot to input it, to re-prompt them to do it again. So far im using a String value and the '.startsWith()' code, but I'm finding later on that a String value is making the rest of the program impossible to code, so i was wanting to keep it a double value. This is the code I have at the moment but wish to change to a double:
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
I was wanting to replace the String with double as mentioned previously.
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
// if your excution reaches here. then it means the values entered by user is starting from '#'.
String temp = input;
double value = Double.parseDouble(temp.replace("#",""));
For the rest of the program use value. I think the coding should be possible now.
A double value doesn't have a currency symbol. You should check for the currency symbol as you are doing and remove it before parsing the double.
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("£")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
doulble number = Double.parseDouble(input.substring(1));
You should use the startsWith method. I don't know why you say that
I'm finding later on that a String value is making the rest of the program impossible to code
Basically, you want to prompt it repeatedly until the user enters the # sign. So why not use a while loop?
System.out.println("Enter a number:");
String s = keyboard.next();
double d = 0.0; // You actually wnat to store the user input in a
// variable, right?
while (!s.trim().startWith("#")) {
System.out.println("You did not enter the number in the correct format. Try again.");
s = keyboard.next();
try {
d = Double.parseDouble(s.substring(1));
} catch (NumberFormatException ex) {
continue;
} catch (IndexOutOfBoundsException ex) {
continue;
}
}
That's a lot of code!
Explanation:
First, it prompts the user to enter a number and store the input in s. That's easy to understand. Now here comes the hard part. We want to loop until the user enters the input with the correct format. Let's see what kind of invalid inputs are there:
The user does not enter a # sign
The user does not enter a number
The first one is handled by the startsWith method. If the input does not start with #, ask the user again. Before that, trim is first called to trim off whitespace in the input so that input like " #5.90" are valid. The second is handled by this part:
try {
d = Double.parseDouble(s.substring(1));
} catch (NumberFormatException ex) {
continue;
} catch (IndexOutOfBoundsException ex) {
continue;
}
If the input is in a wrong format, ask the user again. If the user enters a string with a length less than 1, ask the user again.
"But wait! Why is there a call to the substring method?" you asked. If the user does enter a # in the front, followed by a correct number format, how would you convert that string to a double? Here I just kind of trim the first character off by calling substring.
You could try something like this which removes all character that's not a number or a point:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
System.out.println("Input a number: ");
while (!(input = br.readLine()).equals("quit")) {
Double parsedDouble;
if (input.matches("#[0-9]+\\.[0-9]{1,2}")) {
parsedDouble = Double.parseDouble(input.replaceAll("[^0-9.]+", ""));
System.out.println("double: " + parsedDouble);
System.out.println("Input another number: ");
} else {
System.out.println("Invalid. Try again. Example: #10.10");
}
}
}

Java Strange String Spacing Issue

I am creating a java program that uses a cipher to encode any message the user types in. It works flawlessly with single words like "hello" and "testing", but begins to fall apart when you add spaces, like the message "hello world." Here is the code:
import java.util.Scanner;
import java.util.ArrayList;
public class Code {
public static void main(String[] args) {
Scanner shiftValue = new Scanner(System.in);
System.out.print("Please enter shift value: ");
int shift = shiftValue.nextInt();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Scanner input = new Scanner(System.in);
String codeInput = "anything";
int index = 0;
while(!codeInput.equals("end")) {
System.out.println();
System.out.println("Please enter message: ");
codeInput = input.next();
for(int i = 0; i < codeInput.length(); i++){
if(Character.isWhitespace(codeInput.charAt(i))){
System.out.print(" ");
}
else {
while(alphabet.charAt(index) != codeInput.charAt(i)){
index++;
}
if(index > 25 - shift){
index = index - (26 - shift);
System.out.print(alphabet.charAt(index));
}
else {
System.out.print(alphabet.charAt(index + shift));
}
}
index = 0;
}
}
} //method
} //class
When I type start the program, it asks for a shift value, which decides how many letters to shift the cipher. After that, it goes into a while loop, forever asking the user for input, then outputting an encoded version of the input, until the word "end" is typed. In the eclipse console, it looks like this:
Please enter shift value: 3
Please enter message:
hello
khoor
Please enter message:
testing
whvwlqj
Please enter message:
However, when I type multiple words with spaces between them, it looks like this:
Please enter shift value: 3
Please enter message:
hello world
khoor
Please enter message:
zruog
Please enter message:
For some reason, instead of displaying both words in the same sentence format as the input, it encodes the first word, then goes through the entire while loop again before encoding the second word.
I have no idea why this happens, so I would appreciate any help or advice you guys could give me.
Thank you for reading my post, and have a wonderful day.
The Scanner splits the input for you already and by default by whitespaces.
JavaDoc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Need help splitting a string into two separate integers for processing

I am working on some data structures in java and I am a little stuck on how to split this string into two integers. Basically the user will enter a string like '1200:10'. I used indexOf to check if there is a : present, but now I need to take the number before the colon and set it to val and set the other number to rad. I think I should be using the substring or parseInt methods, but am unsure. The code below can also be viewed at http://pastebin.com/pJH76QBb
import java.util.Scanner; // Needed for accepting input
public class ProjectOneAndreD
{
public static void main(String[] args)
{
String input1;
char coln = ':';
int val=0, rad=0, answer=0, check1=0;
Scanner keyboard = new Scanner(System.in); //creates new scanner class
do
{
System.out.println("****************************************************");
System.out.println(" This is Project 1. Enjoy! "); //title
System.out.println("****************************************************\n\n");
System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
System.out.println("INPUT EXAMPLE: 160:2 {ENTER} "); //example
System.out.print("INPUT: "); //prompts user input.
input1 = keyboard.nextLine(); //assigns input to string input1
check1=input1.indexOf(coln);
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
System.out.println("found ':'");
}
}while(check1==-1);
}
}
Substring would work, but I would recommend looking into String.split.
The split command will make an array of Strings, which you can then use parseInt to get the integer value of.
String.split takes a regex string, so you may not want to just throw in any string in it.
Try something like this:
"Your|String".split("\\|");, where | is the character that splits the two portions of the string.
The two backslashes will tell Java you want that exact character, not the regex interpretation of |. This only really matters for some characters, but it's safer.
Source: http://www.rgagnon.com/javadetails/java-0438.html
Hopefully this gets you started.
make this
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method
//will
// return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
System.out.print("first number = "+ numbers[0]);
System.out.print("Second number = "+ numbers[1]);
}
You knew where : is occurs using indexOf. Let's say string length is n and the : occurred at index i. Then ask for substring(int beginIndex, int endIndex) from 0 to i-1 and i+1 to n-1. Even simpler is to use String::split

Categories

Resources