regular expression in java gui for text box - java

I am trying to perform user input on textbox to check whether they had enter any number or special character in the textbox for their username. I check several resource at online also not able to find out what is my problem inside my code. it's showing me four error message
1) error: 'else' without 'if'
else if(tf3.getText().isEmpty())
2.) error: ';' expected
if(!(Pattern.matches("^[a-zA-Z]$")),tf3.getText())
3.) error: variable declaration not allowed here
if(!(Pattern.matches("^[a-zA-Z]$")),tf3.getText())
4.) error: ';' expected
if(!(Pattern.matches("^[a-zA-Z]$")),tf3.getText())
Here is my full program for my whole program
if(e.getSource()== btn2)
{
if(!(Pattern.matches("^[a-zA-Z]$")),tf3.getText())
{
JOptionPane.showMessageDialog(null,"Please enter a valid name");
}
else if(tf3.getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"Check your name");
}
else if(tf2.getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"Check your id");
}
else if(cmb1.getSelectedIndex()== 0)
{
JOptionPane.showMessageDialog(null,"Check your year");
}
else if(cmb2.getSelectedIndex()== 0)
{
JOptionPane.showMessageDialog(null,"Check your major");
}
else if(cmb3.getSelectedIndex() == 0)
{
JOptionPane.showMessageDialog(null,"Check your selection");
}
else
{
String name = tf3.getText();
String id = tf2.getText();
String job = String.valueOf(cmb1.getSelectedIndex());
String country = String.valueOf(cmb2.getSelectedIndex());
String software = String.valueOf(cmb3.getSelectedIndex());
runCC(software,id,name,job,country);
}
}

Parentheses:
if(!(Pattern.matches("^[a-zA-Z]$")),tf3.getText())
should look like:
if(!Pattern.matches("^[a-zA-Z]$", tf3.getText()))
At least if i got what you meant.

Change
if(!(Pattern.matches("^[a-zA-Z]$")),tf3.getText())
to
if (! Pattern.matches("^[a-zA-Z]$", tf3.getText()))

Ok, since I'm unable to understand what your comments under my answer mean, (not only because i'm drunk!), I'll provide a 'step by step' whats-goin-on:
Pattern class provides a static method: Pattern#matches
It takes two arguments:
First - a string with a regular expression you want to test your string with
Second - a string to test that regex with.
So, whenever you are calling method:
Pattern.matches(regex, string)
You're asking, whether:
"string" matches regular expression "regex"
So in your code you want to say:
"Ok, i want to know, if the text inside tx3 field contains only characters, that are between a-z or between A-Z.
So your regex is: "any sequence of characters, that are between a-z or between A-Z.
That corresponds to
^[a-zA-Z]+$
Now, you call the method that will check, whether your strings matches that regex:
Pattern.matches("%[a-zA-Z]+$", tx3.getText())
That method returns boolean: true, if it matches, or false otherwise.
I don't think anyone will be able to put this more straight-forward.

Related

Do while loop error message

I am a beginner programmer (first post here!) and I cannot figure out how to create an error message with a "do while" loop. If given input that's not in the alphabet it is supposed to display the error message until given an input with only letters and then move on the to rest of the program. My code seems to loop forever even if given correct input. Any suggestions are greatly appreciated! :)
do {
input = JOptionPane.showInputDialog("What is your name?");
if (input.contains("[a-zA-Z]"))
name = input;
else
System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case");
} while (!input.contains("[a-zA-Z]"));
You can show user an error popup so he knows something is wrong with his/her input.
In else statement where you are Printing message just do
JOptionPane.showMessageDialog(frame,
"Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case.",
"Input error",
JOptionPane.ERROR_MESSAGE);
return;
For more information
You use the wrong method to validate your regex. .contains() expects a char sequence. That is not what you want.
You should instead use the .matches() method.
String input = "";
do{
input = JOptionPane.showInputDialog("What is your name?");
if (input.matches("[a-zA-Z]+")) // Replacing the contains()
name = input;
else
System.out.println
("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case");
}while (!input.matches("[a-zA-Z]+")); //Once again replacing contains()
input.contains("[a-zA-Z]") checks if input contains the text [a-zA-Z].
You can use the matches method.
input.matches("[a-zA-z]+")
Also, you should use [a-zA-z]+ as the pattern, since you are trying to match one or more alphabets.
The problem is related to how you check for the given input.
String input;
String name = "";
do {
input = JOptionPane.showInputDialog("What is your name?");
if (input.matches("[a-zA-Z]+")) {
name = input;
} else {
System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case");
}
} while (!input.matches("[a-zA-Z]+"));
using the matches function of string can help you achieve what you want
String.contains() method matches a set of character sequence.
What you've specified is a regular expression, hence, you should be using String.matches() or the Pattern class to perform the check.
It should be something like this using the Pattern class.
Pattern p = Pattern.compile("[a-zA-Z]+");
Matcher m = p.matcher(input);
if(m.matches){
//Do something
}
Refer to this documentation for more details

I want to know how to find a special character in a string

I am programming in Java in Eclipse, I want to ask users to enter their specific ID, Which starts with an uppercase G and has 8 digit numbers. like G34466567. if the user enters an invalid ID it will be an error. how can i separate a valid ID from others?
You can use regex. This pattern checks if the first character is a capital G and there are 8 digits following:
([G]{1})([0-9]{8})$
As you see there are two expressions which are separated by the (). The first says "only one character and this one has to be a capital G". And the second one says, there have to be 8 digits following and the digits can be from 0 to 9.
Every condition contains two "parts". The first with the [] defines which chars are allowed. The pattern inside the {} show how many times. The $ says that the max length is 9 and that there can't be more chars.
So you can read a condition like that:
([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
One condition
And in Java you use it like that:
String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);
As you see that matches method takes two parameters. The first parameter is a regex and the second parameter is the string to check. If the string matches the pattern, it returns true.
Create an ArrayList. Ask the user to input the ID, check if it is already there in the list, ignore, otherwise add that ID to the list.
EDIT: For ensuring that the rest 8 characters of the String ID are digits, you can use the regex "\\d+". \d is for digits and + is for one or more digits.
Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
System.out.println("Pleaes enter you ID.");
ID = sc.next();
if (IDS.contains(ID)) {
System.out.println("This ID is already added.");
} else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
IDS.add(ID);
System.out.println("Added");
} else {
System.out.println("Invalid ID");
}
System.out.println("Do you want to add more? y/n");
more = sc.next().charAt(0);
}
Assuming that you save the id as a string, you can check the first letter and then check if the rest is a number.
Ex.
String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9); //this will give you the number
To check that number is a number you could do the following instead of checking every character:
try {
foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
// this is not a number
}

Java subString/Accept first 3 characters in user input?

I am trying to make my program only accept the users input if the first 3 characters in their input/string, match the first 3 characters to an item of mine in my array.
This is what I have so far to check the input...
private static void checkInput(String[] items, String itemInput)
{
boolean found = false;
for (String item : items)
{
if (item.startsWith(itemInput.subString(0, 3)))
{
found = true;
}
}
if (!found)
{
System.out.println("ERROR. You must enter a valid item. (Exiting Program)");
System.exit(0);
}
}
It appears to be complaining on the subString part. "if(item.startsWith(itemInput.subString(0,3){"
symbol: method subString(int, int)
location: variable itemInput of type String.
How can I fix this? So the user can input simply 3 of the first letters of an item stored in my array, and it pass through as true and proceeds on with the program?
The method substring is all lower case (not subString).
See for references http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
Your problem is that substring should be all lower case. This is simply the only problem I can find.

Java - validating a subject Code

I have a subject code e.g: ABC123 that is a string
I need to ensure that it is of length 6, the first 3 characters are letters and the last 3 are numbers.
I would like to try and do it all in an if statement? I can work the length but cannot figure out the numeric and letter part of things. e.g:
public void isValidCode(String subjectCode2){
str = subjectCode2;
if (str.length() == 6 && """"NEED TO TEST OTHERS HERE??""" ) {
System.out.println("The code is valid");
}
else {
System.out.println("The code is not valid");
}
You can always use Regular Expressions, and the matches() method of the String class.
if (str.matches("[a-zA-Z]{3}[0-9]{3}")) {
// Validation succeeded
}
else {
// Validation failed
}
To test that the first three letters are letters, you could use a loop. Similarly, use a loop for testing that the last three digits are numbers. You might find the functions in the Character class helpful.
I would change the method signature so that it is not a void method but rather declared to return a boolean. Then you could have several if statements that if false returns false. At the bottom, return true if it passes all tests.
public boolean isValidCode(String code) {
if (code.length() != 6) {
return false;
}
// here check if first 3 chars are letters
// here check if last 3 chars are numbers
return true;
}
Then the calling code can do a println if desired.
String test = "ABC123";
if (isValidCode(test)) {
System.out.println("The code is valid");
} else {
System.out.println("The code is not valid");
}
If by "letter", you mean to include letters in alphabets other than English, you'll need this.
if (str.matches("\\p{L}{3}\\d{3}")) {
Here, \p{L} matches any character that Unicode considers to be a letter, in any language.

Java - See if a string contains any characters in it

The problem i'm having is when i check to see if the string contains any characters it only looks at the first character not the whole string. For instance I would like to be able to input "123abc" and the characters are recognized so it fails. I also need the string to be 11 characters long and since my program only works with 1 character it cannot go any further.
Here is my code so far:
public static int phoneNumber(int a)
{
while (invalidinput)
{
phoneNumber[a] = myScanner.nextLine();
if (phoneNumber[a].matches("[0-9+]") && phoneNumber[a].length() == 11 )
{
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
For instance why if i take away the checking to see the phoneNumber.length() it still only registers 1 character so if i enter "12345" it still fails. I can only enter "1" for the program to continue.
If someone could explain how this works to me that would be great
Your regex and if condition is wrong. Use it like this:
if ( phoneNumber[a].matches("^[0-9]{11}$") ) {
System.out.println("Continue");
invalidinput = false;
}
This will only allow phoneNumber[a] to be a 11 character long comprising only digits 0-9
The + should be outside the set, or you could specifically try to match 11 digits like this: ^[0-9]{11}$ (the ^ and $ anchor the match to the start and end of the string).
You need to put the "+" after the "]" in your regex. So, you would change it to:
phoneNumber[a].matches("[0-9]+")
Why not try using a for loop to go through each character?
Like:
public static int phoneNumber(int a)
{
while (invalidinput)
{
int x = 0;
for(int i = 0; i < phoneNumber[a].length(); i++)
{
char c = phoneNumber[a].charAt(i);
if(c.matches("[0-9+]")){
x++;
}
}
if (x == phoneNumber[a].length){
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
Are the legal characters in your phone numbers 0..9 and +? If so, then you should use the regular expression [0-9+]*, which matches zero or more legal characters. (If not, you probably meant [0-9]+.) Also, you can use [0-9+]{11} instead of your explicit check for a length of 11.
The reason that your current code fails, is that String#matches() does not check whether the regular expression matches part of the string, but whether it matches all of the string. You can see this in the JavaDoc, which points you to Matcher#matches(), which "Attempts to match the entire region against the pattern."

Categories

Resources